Leetcode

Sum of Two Integers

  • Time:O(32)
  • Space:O(1)

C++

class Solution {
 public:
  int getSum(unsigned a, unsigned b) {
    while (b) {                      // still have carry bits
      const unsigned carry = a & b;  // record carry bits
      a ^= b;                        // ^ works like + w/o handling carry bits
      b = carry << 1;
    }
    return a;
  }
};

JAVA

class Solution {
  public int getSum(int a, int b) {
    while (b != 0) {           // still have carry bits
      final int carry = a & b; // record carry bits
      a ^= b;                  // ^ works like + w/o handling carry bits
      b = carry << 1;
    }
    return a;
  }
}

Python

class Solution:
  def getSum(self, a: int, b: int) -> int:
    mask = 0xFFFFFFFF
    kMax = 2000

    while b:
      a, b = (a ^ b) & mask, ((a & b) << 1) & mask

    return a if a < kMax else ~(a ^ mask)