AdSense

Sunday, August 21, 2016

Sum of Two Integers

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.


Binary operations. Using XOR for the sum and AND for the carry.
Think it in a binary way. If two bits are both 1, then adding them will lead a 0 and a 1 in the next position. So a^=b gives us the result of current bit and a&b gives us the carry. We then move the carry to next bit.


public int getSum(int a, int b) {
        while (b != 0) {
            int carry = a & b;
            a ^= b;
            b = carry << 1;
        }
        return a;
    }

No comments:

Post a Comment