A straightforward solution in Java


  • 0
    H
        public int getSum(int a, int b) {
                int mask = 1;//bit mask to get every bit of a,b
                int result = 0;
                int carryBit = 0;
                for (int i = 0; i < 32; i++)
                {
                    int num1 = a & mask;
                    int num2 = b & mask;
                    result |= num1 ^ num2 ^ carryBit;
                    if ((num1 & num2) !=0 || (num1 & carryBit)!=0 || (num2 & carryBit)!=0)//if two of three numbers(num1,num2,carryBit) in current bit are 1,that makes a carry,for example,0010+0010+00010 makes a carry in 2th bit 
                        carryBit |= (num1 == 1 ? num1 : num2);
                    else
                        carryBit = 0;
                    mask = mask << 1;
                    carryBit = carryBit << 1;
                }
                return result;
        }
    

  • 0
    R

    even more concise:

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.