Skip to main content
75

Sum of Two Integers

Mediumbit manipulation

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Bit ManipulationRead the beginner guide

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

Understand the problem

  • You need a + b, but you're not allowed to write + or -.
  • Instead, build addition out of bitwise operators (&, |, ^, <<), which work on the binary digits of the numbers.
  • The numbers can be negative.

Example 1

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

Example 2

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

Example 3

text
Input:  a = -5, b = -7
Output: -12

Constraints

  • -1000 <= a, b <= 1000

Note

The tests can't see which operators your code uses. The point is to build addition out of bitwise operations, the way hardware does.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    XOR adds two numbers while ignoring carries, AND-then-shift finds the carries; keep adding the carries back in the same way until there are none left.

    Adding in binary, by hand

    Adding two bits gives a sum bit and a carry, just like adding digits in school (7 + 5 = 12: write 2, carry 1):

    absum bitcarry
    0000
    0110
    1010
    1101

    Look at the columns:

    • The sum bit is 1 when the bits are different: that's exactly XOR (a ^ b).
    • The carry is 1 when both are 1: that's exactly AND (a & b). The carry belongs in the next position to the left, so shift it: (a & b) << 1.

    The key insight: repeat until there's no carry

    Applying this to all bits at once:

    1. sum = a ^ b: every position added, ignoring carries.
    2. carry = (a & b) << 1: all the carries, moved to where they belong.
    3. Now the answer is sum + carry, which is the same problem again. Set a = sum, b = carry, and repeat.

    Each round, the carries move at least one position left, so after at most 32 rounds there are none, and a is the answer.

    Step by step

    a = 5 (0101), b = 3 (0011):

    Roundaba ^ b (new a)(a & b) << 1 (new b)
    10101001101100010
    20110001001000100
    30100010000001000
    40000100010000000

    b is 0, so the answer is a = 1000 = 8. ✓

    Negative numbers

    Computers store negative integers in two's complement: -1 is all 1s, -2 is ...11110, and so on. The same XOR/AND trick works on them, as long as the numbers have a fixed width.

    • JavaScript bitwise operators always work on 32-bit integers, so carries past bit 31 just disappear and negatives come out right. The plain loop works.
    • Python integers have no fixed width, so a negative carry would keep shifting left forever. The Python solution keeps every value inside 32 bits with & 0xFFFFFFFF (a mask of 32 ones). At the end, if bit 31 is set, the result is a negative number, and ~(a ^ MASK) converts it back to a Python negative.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(1). At most 32 rounds.
    • Memory: O(1).

    Common mistakes

    • Forgetting to shift the carry left. The carry goes into the next position.
    • Updating a before computing the carry from the old a. Compute the carry first (or both from the old values).
    • In Python, an infinite loop with negative numbers, because integers don't have 32 bits. Use the mask.

    Going deeper

    This is how a computer's processor actually adds numbers: a circuit called an adder uses exactly these XOR and AND gates. Subtraction can be built on top of it: a - b = a + (~b + 1), because ~b + 1 is -b in two's complement.

    Reference solution

    js
    /**
     * @param {number} a
     * @param {number} b
     * @return {number}
     */
    export default function getSum(a, b) {
      // b holds the carries still to add. Stop when there are none.
      while (b !== 0) {
        const carry = (a & b) << 1 // both bits 1 → carry into the next position (from the OLD a)
        a ^= b // add every position, ignoring carries
        b = carry // now add the carries the same way
      }
      return a
    }
    ts
    export default function getSum(a: number, b: number): number {
      // b holds the carries still to add. Stop when there are none.
      while (b !== 0) {
        const carry = (a & b) << 1 // both bits 1 → carry into the next position (from the OLD a)
        a ^= b // add every position, ignoring carries
        b = carry // now add the carries the same way
      }
      return a
    }
    python
    # Python ints have no fixed size, so we simulate 32-bit integers with a mask of 32 ones.
    MASK = 0xFFFFFFFF
    MAX_INT = 0x7FFFFFFF  # the largest positive 32-bit value
    
    
    def get_sum(a: int, b: int) -> int:
        a &= MASK
        b &= MASK
        # b holds the carries still to add. Stop when there are none.
        while b:
            carry = ((a & b) << 1) & MASK  # both bits 1 → carry into the next position
            a = (a ^ b) & MASK  # add every position, ignoring carries
            b = carry  # now add the carries the same way
        # Bit 31 set means negative in 32-bit two's complement: convert to a Python negative.
        return a if a <= MAX_INT else ~(a ^ MASK)