Sum of two numbers with bitwise operator

♀尐吖头ヾ 提交于 2019-11-30 02:59:11

Think in entire 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, as the carry has consecutively more bits 0 at the right (at most 32 iterations).

One can easily write it as a loop with p = result; q = carry;.

Another feature in algorithmic exploration is not going too far in differentiating cases. Above you could also take the condition: if ((result & carry) != 0).

I think that the optimizations should be in the field of readability, rather than performance (which will probably be handled by the compiler).

Use for loop instead of while

The idiom for (int i=0; i<32; i++) is more readable than the while loop if you know the number of iterations in advance.

Divide the numbers by two

Dividing the numbers by two and getting the modulu:

n1 = p % 2;
p  /= 2;

Is perhaps more readable than:

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

I think below soln is easy to understand & 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);    
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!