The sum of two numbers with a bitwise operator

I insert the code to find the sum of two numbers with a bitwise operator. Please suggest if it can be optimized. Thank...

public static int getSum(int p, int q)
{
int carry=0, result =0;
for(int i=0; i<32; i++)
{
    int n1 = (p & (1<<(i)))>>(i); //find the nth bit of p
    int n2 = (q & (1<<(i)))>>(i); //find the nth bit of q

    int s = n1 ^ n2 ^ carry; //sum of bits
    carry = (carry==0) ? (n1&n2): (n1 | n2); //calculate the carry for next step
    result = result | (s<<(i)); //calculate resultant bit
}

return result;
}
+6
source share
3 answers

Think in whole bits:

public static int getSum(int p, int q)
{
    int result = p ^ q; // + without carry 0+0=0, 0+1=1+0=1, 1+1=0
    int carry = (p & q) << 1; // 1+1=2
    if (carry != 0) {
        return getSum(result, carry);
    }
    return result;
}

This recursion ends because the transfer has successively more bits 0 on the right (maximum 32 iterations).

You can easily write this as a loop with p = result; q = carry; p = result; q = carry;,

Another feature of algorithmic research does not go too far in differentiating cases. Above, you can also take the condition if ((result & carry) != 0).

+25
source

I think that optimization should be in the area of ​​readability, not performance (which is likely to be handled by the compiler).

for (int i=0; i<32; i++) , while, .

:

n1 = p % 2;
p  /= 2;

, , :

(p & (1<<(i-1)))>>(i-1);
+2

I think below Soln is easy to understand and simple,

public static void sumOfTwoNumberUsingBinaryOperation(int a,int b)
{
    int c = a&b;
    int r = a|b;
    while(c!=0)
    {
        r =r <<1;
        c = c >>1;      
    }
    System.out.println("Result:\t" + r);    
}
0
source

All Articles