Loading

LeetCode problem#371

Sum of Two Integers

Solved in 4 languagesRubyC#PythonJava

Solve it on LeetCode(opens in a new tab)

Solution

16 lines
1# @param {Integer} a
2# @param {Integer} b
3# @return {Integer}
4def get_sum(a, b)
5  mask = 0xFFFFFFFF # 8 * 4 = 32 bits
6  while (b != 0)
7      carry = (a & b) << 1
8      a = (a ^ b) & mask
9      b = carry & mask
10  end
11  if a <= 0x7FFFFFFF # (2^32) / 2 - 1 is the maximum possible value for a 32-bit integer
12      return a
13  else
14      return ~(a ^ mask)
15  end
16end
1public class Solution {
2    public int GetSum(int a, int b) {
3        while (b != 0) {
4            int carry = (a & b) << 1;
5            a ^= b;
6            b = carry;
7        }
8        return a;
9    }
10}
1class Solution:
2    def getSum(self, a: int, b: int) -> int:
3        # To avoid Time Limit Exceeded
4        mask = 0xFFFFFFFF # 32 bits
5        while (b & mask) != 0:
6            carry = (a & b) << 1
7            a = a ^ b
8            b = carry
9        
10        if b > 0:
11            return a & mask
12        else:
13            return a
1class Solution {
2    public int getSum(int a, int b) {
3        while (b != 0) {
4            int carry = (a & b) << 1;
5            a = a ^ b;
6            b = carry;
7        }
8        return a;
9    }
10}

Want a walkthrough of this Ruby solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.