Sum of Two Integer

By | July 1, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

leetcode 371. 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.

Soltuion is from here. Each time, we use xor to calculate current sum, and to calculate current carrier. Loop this until carrier is zero.

public static int getSum(int a, int b) {
    /*
    sum = a ^ b
    carrier = (a & b) << 1
     */
    while (b != 0) {
        int sum = a ^ b;    // to get the current sum
        b = (a & b) << 1;   // to get the carrier
        a = sum;
    }
    return a;
}

Check my code on github: link

  • junmin liu

    hehe, i was looking at the same prblem yesterday

    • http://www.allenlipeng47.com peng li

      how are you junmin? I’ve been very lazy practicing for a long time.