Loading
Leetcode / 371. Sum of Two Integers

Pick a programming language:

Here is the source code for the solution to this problem.

# @param {Integer} a
# @param {Integer} b
# @return {Integer}
def get_sum(a, b)
  mask = 0xFFFFFFFF # 8 * 4 = 32 bits
  while (b != 0)
      carry = (a & b) << 1
      a = (a ^ b) & mask
      b = carry & mask
  end
  if a <= 0x7FFFFFFF # (2^32) / 2 - 1 is the maximum possible value for a 32-bit integer
      return a
  else
      return ~(a ^ mask)
  end
end
public class Solution {
    public int GetSum(int a, int b) {
        while (b != 0) {
            int carry = (a & b) << 1;
            a ^= b;
            b = carry;
        }
        return a;
    }
}
class Solution:
    def getSum(self, a: int, b: int) -> int:
        # To avoid Time Limit Exceeded
        mask = 0xFFFFFFFF # 32 bits
        while (b & mask) != 0:
            carry = (a & b) << 1
            a = a ^ b
            b = carry
        
        if b > 0:
            return a & mask
        else:
            return a
class Solution {
    public int getSum(int a, int b) {
        while (b != 0) {
            int carry = (a & b) << 1;
            a = a ^ b;
            b = carry;
        }
        return a;
    }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: