Recently came across an interesting question of adding two numbers without using any of the arithmetic operators and thought of giving it a try.
The first thought of solving the question was using bit-manipulation operations. The idea was to add the numbers bit-by-bit taking any carry forward (without actually adding them and instead using bit-wise AND/OR/XOR operators) just as we were taught to do normal arithmetic in primary classes except that here we are dealing with binary numbers instead of decimals.
The code for the same follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
package com.coddicted; /** * @author Coddicted * Class to add two integers without * using any arithmetic operator */ public class AddWithoutPlus { /** * @param num The number from which to get the bit value * @param pos The 0 based index position of which to get the bit value * @return * The 0/1 bit value at the specified index position <code>pos</code> of * number <code>num</code> */ public static int getBit(int num, int pos){ return (num>>pos)&1; } /** * @param num * @param pos * @param set * @return * Sets/Resets the bit at index <code>pos</code> of number <code>num</code> * based on whether <br> the boolean <code>set</code> flagis set to <code>true</code> * or is reset to <code>false</code>.<br> * Finally returns the new number after set/reset operation. */ public static int setBit(int num, int pos, boolean set){ int b = (1<<pos); if(set){ num |= b; } else { num &= (~b); } return num; } /** * @param a * @param b * @return * Result of adding a and b. */ public static int addWithoutArithmetic(int a, int b){ // Initialize variables. // Assuming initial sum to be zero. int sum = 0, index = 0, carry = 0; int bita, bitb, bit; while(index < 32){ // Get the individual bits at corresponding indexes // from both the numbers. bita = getBit(a,index); bitb = getBit(b,index); // Get the bit value for current bit position in sum bit = carry ^ (bita ^ bitb); // Set the bit value in sum. if(bit>0) sum = setBit(sum, index, true); // Calculate the carry value // There will be a carry if any of the two bits are 1. if(((bita & bitb) == 1) || ((carry & bita)==1) || ((carry & bitb)==1)){ carry = 1; } else { carry = 0; } // Move to next index. index++; } return sum; } public static void main(String[] args) { int a = 105, b = 19; System.out.println("sum of " + a + " + " + b + " is: " + addWithoutArithmetic(a, b)); } } |
There certainly can be other approaches as well and we would appreciate our readers to share the same if they have any. 🙂
You can get the ‘C’ language version of the above code at Github.