371. Sum of Two Integers

用位运算实现加法,^求和,&左移求进位,进位为0时返回答案

2 + 3
a          b          a        b
010        010       001       001
011 ^      011&      100^      100^ 
----       ----      ----      -----
001        010       101       000       return 5
public int getSum(int a, int b) {
    while (b != 0) {
        int sum = a ^ b;
        int carry = (a & b) << 1;
        a = sum;
        b = carry;
    }
    return a;
}

results matching ""

    No results matching ""