KatInterview

371. Sum of Two Integers

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core of this problem is to compute the sum of two integers, a and b, without using the standard addition (+) and subtraction (-) operators. This constraint forces us to think about how addition is performed at a lower level, specifically using bitwise operations. The fundamental idea is to mimic the behavior of a binary full adder circuit.

Solution

Sum of Two Integers in Python

class Solution:
    def getSum(self, a: int, b: int) -> int:
        # Python's integers have arbitrary precision. To simulate the behavior of
        # fixed-size integers (like 32-bit integers in C++ or Java), we use a mask.
        # 0xFFFFFFFF represents a 32-bit mask.
        mask = 0xFFFFFFFF
        
        # We loop until the carry `b` becomes 0.
        # In Python, negative numbers are represented differently, so we must
        # confine our numbers to 32 bits using the mask.
        while (b & mask) != 0:
            # Calculate carry: (a & b) and then left shift by 1.
            # Mask the result to keep it within 32 bits.
            carry = ((a & b) << 1) & mask
            
            # Calculate sum without carry: a XOR b.
            # Mask the result to keep it within 32 bits.
            a = (a ^ b) & mask
            
            # The new `b` is the carry.
            b = carry
            
        # The result `a` is the 32-bit representation of the sum.
        # If the sum is negative, its 32-bit representation will be a large positive number.
        # We check the sign bit (31st bit). If it's 1, the number is negative.
        if (a >> 31) & 1:
            # To convert this 32-bit representation to a standard Python negative integer,
            # we can compute its two's complement. `~(a ^ mask)` is a concise way to do this.
            # E.g., if a is 0xFFFFFFFF (rep. for -1), a^mask is 0, ~0 is -1.
            return ~(a ^ mask)
        else:
            # If the number is positive, it's already in the correct form.
            return a

Sum of Two Integers in Java

class Solution {
    public int getSum(int a, int b) {
        // The loop continues as long as there's a carry.
        while (b != 0) {
            // Calculate carry. A carry is generated when a bit is 1 in both a and b.
            // (a & b) finds these positions.
            int carry = a & b;
            
            // Calculate sum of bits without carry using XOR.
            // 'a' is updated to this partial sum.
            a = a ^ b;
            
            // Shift carry to the left by one position. This is because a carry
            // from bit i should be added to bit i+1.
            // 'b' is updated to hold the carry for the next iteration.
            b = carry << 1;
        }
        // When carry (b) becomes 0, the loop terminates, and 'a' holds the correct sum.
        return a;
    }
}

Sum of Two Integers in C++

class Solution {
public:
    int getSum(int a, int b) {
        // The loop continues as long as there is a carry (b != 0).
        while (b != 0) {
            // 'carry' will store the bits that need to be carried over.
            // A carry occurs where both a and b have a 1.
            // We use unsigned int for carry to avoid undefined behavior
            // when left-shifting a negative number (which can happen if MSB of a&b is 1).
            // (a & b) gives the bits that are set in both a and b.
            unsigned int carry = (unsigned int)(a & b) << 1;
            
            // a XOR b gives the sum of bits without considering the carry.
            // 'a' is updated to this partial sum.
            a = a ^ b;
            
            // The carry is shifted left by 1 because a carry from bit i
            // needs to be added to bit i+1.
            // 'b' is updated to be the carry for the next iteration.
            b = carry;
        }
        // When the carry 'b' becomes 0, 'a' holds the final sum.
        return a;
    }
};

Sum of Two Integers in TypeScript

function getSum(a: number, b: number): number {
    // In JavaScript/TypeScript, bitwise operators work on 32-bit signed integers.
    // The operands are converted to 32-bit integers, the operation is performed,
    // and the result is converted back to a standard JavaScript number.
    // This makes the logic similar to C++ and Java.
    
    // The loop continues as long as there is a carry.
    while (b !== 0) {
        // Calculate the carry. `a & b` finds bits set in both numbers.
        // Left-shifting by 1 prepares the carry for the next bit position.
        const carry = (a & b) << 1;
        
        // Calculate the sum of bits without considering the carry.
        a = a ^ b;
        
        // Update `b` to be the carry for the next iteration.
        b = carry;
    }
    
    // When `b` is 0, `a` holds the final sum.
    return a;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.