Sum of Two Integers
Part of Practice: Arithmetic Without +
Given two integers a and b, return their sum — but you may not use the + or - operators anywhere. Both values can be negative, and both fit comfortably in a 32-bit signed integer (the constraint keeps them between -1000 and 1000).
The intended tool is bitwise arithmetic: reconstruct what the CPU's adder circuit does with AND, XOR, and shifts.
Examples
- Input:
- a = 1, b = 2
- Output:
- 3
- Input:
- a = 2, b = 3
- Output:
- 5
In binary: 10 + 11. XOR gives 01 (sum without carry); AND<<1 gives 100 (the carry). 01 + 100 = 101 = 5.
- Input:
- a = -2, b = 3
- Output:
- 1
Two's complement bit patterns make the same XOR/carry loop work for negative numbers.
Hints
One at a time — struggle first, peek second.
Your thinking space — verify on LeetCode, then mark it.