371. Sum of Two Integers - cocoder39/coco39_LC GitHub Wiki

371. Sum of Two Integers

sum is the sum representation of adding two bits, sum_bit == 1 iff (a_bit == 1 && b_bit == 0) || (a_bit == 0 && b_bit == 1). carry is the carry bit generated from adding each bit, carry_bit == 1 iff a_bit == 1 && b_bit == 1. The carry_bit would be used in computing the addition of a higher bit.

Thus the next addition is sum + (carry << 1)

int getSum(int a, int b) {
        while (b != 0) {
            int carry = a & b; //carry generated from each bit
            a = a ^ b; // sum of each bit
            b = (carry << 1);
        }
        return a;
    }