371. Sum of Two Integers LeetCode Solution

In this guide, you will get 371. Sum of Two Integers LeetCode Solution with the best time and space complexity. The solution to Sum of Two Integers problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Sum of Two Integers solution in C++
  4. Sum of Two Integers solution in Java
  5. Sum of Two Integers solution in Python
  6. Additional Resources
371. Sum of Two Integers LeetCode Solution image

Problem Statement of 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

Complexity Analysis

  • Time Complexity: O(32)
  • Space Complexity: O(1)

371. Sum of Two Integers LeetCode Solution in C++

class Solution {
 public:
  int getSum(unsigned a, unsigned b) {
    while (b > 0) {                  // Still have carry bits.
      const unsigned carry = a & b;  // Record the carry bits.
      a ^= b;  // ^ works like + without handling carry bits.
      b = carry << 1;
    }
    return a;
  }
};
/* code provided by PROGIEZ */

371. Sum of Two Integers LeetCode Solution in Java

class Solution {
  public int getSum(int a, int b) {
    while (b != 0) {           // Still have carry bits.
      final int carry = a & b; // Record the carry bits.
      a ^= b;                  // ^ works like + without handling carry bits.
      b = carry << 1;
    }
    return a;
  }
}
// code provided by PROGIEZ

371. Sum of Two Integers LeetCode Solution in Python

class Solution:
  def getSum(self, a: int, b: int) -> int:
    mask = 0xFFFFFFFF
    kMax = 2000

    while b != 0:
      a, b = (a ^ b) & mask, ((a & b) << 1) & mask

    return a if a < kMax else ~(a ^ mask)
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.