You are given two integers, a and b. Return their sum, but without using the + or - operators anywhere in your code.
Either number may be negative.
Example 1
Input: a = 11, b = 5 Output: 16 Why: 1011 + 0101 = 10000 in binary
2 more examples and the constraints
Example 2
Input: a = -4, b = 9 Output: 5 Why: a negative number is added the same way
Example 3
Input: a = 0, b = -6 Output: -6 Why: adding 0 changes nothing
Constraints
- −1,000 ≤ a, b ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Add column by columnO(1)
- XOR and carry, all bits at onceO(1)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for one sum of 32-bit numbers | Verdict |
|---|---|---|---|
| Add column by column | O(1) | Passes; always 32 rounds | |
| XOR and carry, all bits at once | O(1) | Best; stops when carries end |
Both are bounded by the 32 bits of an int; the second usually needs only a few rounds.
Edge cases to test
- A negative number. Example 2: two's complement makes −4 + 9 work with the same bit steps.
- Both negative. −1,000 + −1,000 = −2,000; the top bits stay set.
- Zero. Example 3: when b is 0 the loop never runs and a comes back as is.
- Opposites. −1 + 1 = 0: the carry ripples all the way to the top and drops off.
Common mistakes
- In Python, looping without a 32-bit mask, so a negative carry never dies out.
- Forgetting to turn the masked Python result back into a negative number.
- Shifting before the AND,
a & (b << 1), which is not the carry.
How to talk through it
- 1Clarify. Are negative numbers allowed? Is
++also off limits? What integer size do we assume? - 2Recall binary addition. Per bit, the sum is an XOR and the carry is an AND moved one place left.
- 3Give the column version. Walk 32 positions with a carry, like adding on paper.
- 4Do all bits at once. Loop a = a ^ b, b = carries until b is 0; mention the Python mask.
- 5Test out loud. Run 11 + 5, a negative plus a positive, and −1 + 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?