Algorithm


Problem Name: 371. Sum of Two Integers

Problem Link: https://leetcode.com/problems/sum-of-two-integers/

Given two integers a and b, return the sum of the two integers without using the operators + and -.

 

Example 1:

Input: a = 1, b = 2
Output: 3

Example 2:

Input: a = 2, b = 3
Output: 5

 

Constraints:

  • -1000 <= a, b <= 1000

 

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const getSum = function(a, b) {
  return b === 0 ? a : getSum(a ^ b, (a & b) << 1);
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
a = 1, b = 2

Output

x
+
cmd
3

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def getSum(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        mx, mask = 0x7FFFFFFF, 0xFFFFFFFF
        while b:
            a, b = (a ^ b) & mask, ((a & b) << 1) & mask
        return a if a <= mx else ~(a ^ mask)
Copy The Code & Try With Live Editor

Input

x
+
cmd
a = 1, b = 2

Output

x
+
cmd
3
Advertisements

Demonstration


Previous
#368 Leetcode Largest Divisible Subset Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#372 Leetcode Super Pow Solution in C, C++, Java, JavaScript, Python, C# Leetcode