Sum of two numbers with bitwise operator

后端 未结 3 1939
旧巷少年郎
旧巷少年郎 2021-02-03 15:07

I am pasting the code to find the sum of two numbers with bitwise operator. Please suggest if it can be optimized. Thanks...

public static int getSum(int p, int          


        
3条回答
  •  粉色の甜心
    2021-02-03 15:34

    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).

提交回复
热议问题