Add Two Numbers With Bit Operation

Question:

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 Operation
  • XOR (^) to add two binary bits
  • AND (&) to get carrier of two binary bits add operation
Steps,

1, Get the carrier (c) by (&) operation of two numbers (a, b)
2, Add (^) two number without counting carrier to a
3, left shift carrier one bit to b
4, if carrier is not 0 add it to a with repeat steps above

Solution,
public class _371SumTwoIntegers {  
    public static void main(String[] args) {
        System.out.println(getSum(3, 5));
    }

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