LeetCode Solutions

371. Sum of Two Integers

Time: $O(32)$

Space: $O(1)$

			

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;
  }
};
			

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;
  }
}
			

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)