Skip to content

371. Sum of Two Integers 👎

  • Time: $O(32)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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;
  }
}
1
2
3
4
5
6
7
8
9
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)