Add Two Numbers Without Plus or Minus
You get two integers a and b. Return their sum a + b.
The goal of this exercise is to do it without the + and - operators. Use bit operations instead.
Note
The judge only checks the number you return. It cannot see how you computed it. The rule is there so you practise the bit method. Writing return a + b passes the tests but teaches you nothing.
Hint
a ^ badds the two numbers bit by bit without carrying.(a & b) << 1is the carry: the places where both bits are 1, moved one place left.- Repeat with the new pair (sum without carry, carry) until the carry is
0.
Note for Python
Python integers have no fixed size, so a negative carry never runs out and the loop never ends. Keep every value inside 32 bits with & 0xFFFFFFFF. At the end, if the result is bigger than 0x7FFFFFFF, it stands for a negative number: turn it back with ~(result ^ 0xFFFFFFFF).
Examples
Example 1
- Input:
- 13, 29
- Output:
- 42
13 + 29 = 42.
Example 2
- Input:
- -17, 5
- Output:
- -12
-17 + 5 = -12. The method also works for negative numbers.
Example 3
- Input:
- 250, -250
- Output:
- 0
The two numbers cancel, so the sum is 0.
Constraints
-1000 <= a, b <= 1000
Run checks your code against the 3 examples. Submit checks it against all 253 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.