Sum of Two Integers solution explained
The Sum of Two Integers solution adds without the + operator by splitting addition into two bitwise parts: a ^ b gives each column's sum ignoring carries, and (a & b) << 1 gives the carries moved one place left. Repeat with those two values until the carry is zero. For 32-bit integers this ends within 32 rounds; in Python you must mask to 32 bits and convert back to a signed value, because Python integers have no fixed width.
By Evin JohnPublished 8 min read
The problem in plain words
You get two integers that fit in a signed 32-bit type. Return their sum, but you may not use the addition or subtraction operators. The intent is that you build addition yourself from bit operations, the way a processor's adder circuit does. Ask what should happen if the true sum does not fit in 32 bits; the usual answer is that it wraps around, as it would in hardware.
| a | b | Result | Note |
|---|---|---|---|
| 7 | 5 | 12 | Two carry rounds |
| -9 | 4 | -5 | A negative and a positive |
| 6 | -6 | 0 | Opposites cancel; the carry runs off the top |
| 2147483647 | 1 | -2147483648 | Overflow wraps to the most negative value |
| 0 | -1 | -1 | Zero carry from the start |
Why it is asked
It looks like a trick question, but it tests something real: do you understand how numbers are stored? To answer it you need binary addition with carries, two's complement for negative numbers, and the way your language represents integers. The last part trips many candidates. The algorithm is identical in every language, but Python's unbounded integers make the naive loop run forever on negative input, while JavaScript quietly truncates to 32 bits for you.
Follow-up questions
- Subtract without minus. Negate b with two's complement, ~b + 1, using your own add, then add it to a.
- **Multiply without *.** Shift-and-add: for each 1 bit in b, add a shifted to that position.
- Why does the loop terminate? Each round the carry moves one place left; after at most 32 rounds in a 32-bit type it has shifted out.
- A recursive version. add(a, b) = add(a ^ b, (a & b) << 1) with b == 0 as the base case. Same idea, same caveats.
- What about 64-bit inputs? Change the mask width; the logic is unchanged.
How binary addition splits into two operations
Add two bits in a column and there are four cases: 0 + 0 = 0, 0 + 1 = 1, 1 + 0 = 1, and 1 + 1 = 0 with a carry of 1 into the next column. The column result without the carry is exactly XOR. The carry appears only when both bits are 1, which is AND, and it belongs one column to the left, hence the shift. So a + b is the same as (a ^ b) + ((a & b) << 1). That still contains a plus, but it is a plus of two new numbers, and repeating the split eventually leaves a carry of zero.
Trace 7 + 5. In binary, 0111 and 0101. Round one: XOR is 0010 and the carry is 0101 shifted, 1010. Round two: 0010 and 1010 give XOR 1000 and carry 0100. Round three: 1000 and 0100 give XOR 1100 and carry 0. Stop: 1100 is 12.
A first answer: one full adder per column
The most literal approach copies what a chip does. Walk the 32 bit positions from lowest to highest, read one bit from each number, and combine them with the carry from the previous column: the sum bit is the XOR of all three, and a carry goes out when at least two of the three are 1. It always takes exactly 32 steps and is easy to justify, but it does a lot of single-bit work. The loop in the next sections handles all 32 columns at once in each round.
def add_by_columns(a, b):
result, carry = 0, 0
for i in range(32): # one full adder per bit position
x = (a >> i) & 1
y = (b >> i) & 1
result |= (x ^ y ^ carry) << i
carry = (x & y) | (carry & (x ^ y))
# a set bit 31 means negative: flip the low 32 bits back, then negate all bits
return result if result <= 0x7FFFFFFF else ~(result ^ 0xFFFFFFFF)JavaScript: the language does the width for you
JavaScript converts operands of bitwise operators to signed 32-bit integers and returns a signed 32-bit result. That matches the problem's model exactly, including wrap-around, and the carry eventually shifts past bit 31 and disappears.
function addWithoutPlus(a, b) {
while (b !== 0) {
const carry = (a & b) << 1; // JavaScript bitwise results are 32-bit signed
a = a ^ b;
b = carry;
}
return a;
}Python: mask, then convert back
In Python, -1 is not 32 ones; it behaves like an infinite run of ones to the left. A carry from a negative number keeps moving left forever, and the loop never ends. The fix is to work on the lowest 32 bits only, masking after every shift, and at the end turn a result with the top bit set back into a negative Python integer. The expression ~(a ^ MASK) does that: it flips the low 32 bits back and then applies Python's own negation of all bits, which yields the matching negative number.
MASK = 0xFFFFFFFF
INT_MAX = 0x7FFFFFFF
def add_without_plus(a, b):
a &= MASK
b &= MASK
while b:
carry = ((a & b) << 1) & MASK # positions that produce a carry, moved left
a ^= b # sum of each column, ignoring carries
b = carry
return a if a <= INT_MAX else ~(a ^ MASK) # back to a signed Python intWith the adder in place, subtraction follows from two's complement: the negative of b is its bitwise NOT plus one.
def subtract_without_minus(a, b):
return add_without_plus(a, add_without_plus(~b, 1)) # a + (-b), with -b = ~b + 1Cost
| Approach | Time | Extra memory | Notes |
|---|---|---|---|
| XOR plus shifted AND, looped | O(w), at most 32 rounds | O(1) | The expected answer |
| Recursive version | O(w) calls | O(w) call stack | Equivalent; slightly more memory |
| Column-by-column full adder | Exactly w steps | O(1) | Closer to hardware; more code to write |
Inputs to test
- Two positives with carries, such as 7 and 5.
- A positive and a negative whose sum is negative, such as -9 and 4.
- Opposites such as 6 and -6, which produce a long chain of carries that runs off the top.
- The largest 32-bit value plus 1, which must wrap to the smallest.
- The smallest value plus -1, which wraps the other way.
- Zero on either side, which should return the other number unchanged.
Common slips
- Running the unmasked loop in Python on a negative input and waiting forever.
- Masking during the loop in Python but forgetting the conversion at the end, so -5 comes back as 4294967291.
- In JavaScript, using
>>>for the carry, which is a right shift and moves it the wrong way. - Computing the new carry from the already updated a, instead of from the old a and b. Save the carry first.
- Claiming O(1) without saying why: the number of rounds is bounded by the bit width.
How to explain it out loud
Fictional example
- Candidate
- Adding two bits gives a sum bit and maybe a carry. The sum bit is XOR, the carry is AND, and the carry belongs one column to the left.
- Candidate
- So I replace a and b with a XOR b and the carry shifted left, and repeat. Each round the carry moves left, so in 32-bit arithmetic it is gone after at most 32 rounds.
- Candidate
- In Python I'll mask to 32 bits because its integers are unbounded, then turn a result with the sign bit set back into a negative number. In JavaScript the bitwise operators already work in 32 bits.
Related problems
Reverse Integer is another question about staying inside 32 bits, from the decimal side. Number of 1 Bits and Counting Bits practice the same operators on smaller tasks, and Missing Number shows XOR used as a cancellation tool.
Practicing it with Natively
This problem rewards understanding more than memory. While you practice on a Mac or Windows PC, Natively can read the question from a screenshot, walk through the XOR and carry split with your own numbers, and explain why your Python loop hangs on a negative input. The transcript of your mock session shows whether you mentioned the bit-width bound when you gave the complexity.
Questions people ask
How do you add two integers without the plus operator?
Repeat: carry = (a & b) << 1, a = a ^ b, b = carry, until b is zero. XOR adds each column without carries, and the shifted AND supplies the carries for the next round.
Why does Sum of Two Integers loop forever in Python?
Python integers have no fixed width, so a negative number acts like an endless run of ones and the carry never shifts out. Mask with 0xFFFFFFFF each round and convert the final value back to a signed integer.
How many iterations does the bitwise addition loop take?
At most the bit width, so 32 for 32-bit integers, because the carry moves one position left every round and eventually shifts out of the word.
How do you subtract without the minus operator?
Use two's complement: the negative of b is ~b + 1. Compute it with the bitwise adder, then add it to a.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
