17.01. Add Without Plus
Description
Write a function that adds two numbers. You should not use + or any arithmetic operators.
Example:
Input: a = 1, b = 1 Output: 2
Note:
aandbmay be 0 or negative.- The result fits in 32-bit integer.
Solutions
Solution 1
Thinking
Add without \(+,-,*,/\). A loop that adds would break the rule; simulating pencil-and-paper on strings is longer.
XOR is the sum without carry; AND shifted left is the carry. Repeat until the carry vanishes.
\(sum=a\oplus b\) and \(carry=(a\& b)\ll 1\) are written back into \(a\) and \(b\). The sign bit follows arithmetic shift; the loop is \(O\)(bit width).
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |