LeetCode 371: Sum of Two Integers Solution

Master LeetCode problem 371 (Sum of Two Integers), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

371. Sum of Two Integers

Problem Explanation

Explanation:

To find the sum of two integers without using the + and - operators, we can utilize bitwise operations. The idea is to perform addition using bitwise XOR and carry using bitwise AND left-shift.

Here's how the algorithm works:

  1. Initialize two variables sum and carry.
  2. Calculate the sum of a and b without considering the carry by performing XOR operation: sum = a ^ b.
  3. Calculate the carry by performing AND operation on a and b, then left-shifting it by 1: carry = (a & b) << 1.
  4. Update a with the new sum and b with the new carry.
  5. Repeat steps 2-4 until there is no carry left.

The time complexity of this algorithm is O(1) as the number of iterations is limited by the number of bits in the input integers. The space complexity is O(1) as we are using a constant amount of extra space.

:

Solution Code

class Solution {
    public int getSum(int a, int b) {
        while (b != 0) {
            int sum = a ^ b;
            int carry = (a & b) << 1;
            a = sum;
            b = carry;
        }
        return a;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 371 (Sum of Two Integers)?

This page provides optimized solutions for LeetCode problem 371 (Sum of Two Integers) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 371 (Sum of Two Integers)?

The time complexity for LeetCode 371 (Sum of Two Integers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 371 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 371 in Java, C++, or Python.

Back to LeetCode Solutions