Note: study again. Cool problem!
(a int, b int)
| 2 | |
| 3 | // Note: study again. Cool problem! |
| 4 | func getSum(a int, b int) int { |
| 5 | for b != 0 { |
| 6 | // corresponding bits (1, 1) will need to be set to 0 and carry a 1 over |
| 7 | // carry holds the slots where we'll need to carry |
| 8 | carry := a & b |
| 9 | |
| 10 | // corresponding bits (1, 0) and (0, 1) will stay set |
| 11 | // a no longer has locations of carry bits set via XOR |
| 12 | a = a ^ b |
| 13 | |
| 14 | // set b to the result of carrying over each location that we need to carry in |
| 15 | // eventually all carries will find a slot in a (may take many carries), |
| 16 | // after which b will become 0 and the loop condition will be false. |
| 17 | b = carry << 1 |
| 18 | } |
| 19 | |
| 20 | return a |
| 21 | } |