A + B Problem
ID: 1; naive
Solution 1 (Java)
Solution 2 (Java)
Notes
In order to avoid using the plus sign in this problem, we can use the XOR operation (if two digits are different, the result is 1; otherwise, the result is 0. The XOR operation is essentially adding without carrying. Thus, we can first XOR the two numbers and then add the carry bits.
This means a + b = (a ^ b) + (a & b << 1)
Eventually, the carry bits are zeros (b == 0
) and we end the operation. Example of tracing the code is shown above. We have 14 + 11 = 25, or in binary: 1110 + 1011 = 11011.
Citation
Last updated