Sum of Two Integers
MediumThe problem
Return a + b without using the + or - operators. The numbers can be negative.
- Example 1Input: a = 1, b = 2Output: 3
- Example 2Input: a = -2, b = 3Output: 1
Limits
- -1,000 ≤ a, b ≤ 1,000
- Do not use + or - on the two numbers
Write it in Go. Try for about 20 minutes on paper first, then open one hint at a time.
Try it here
Write Go. Common packages like fmt and sort are imported for you. Keep the function name and inputs the same.
Hints, one at a time
Nudge
XOR adds without carrying. AND shows where carries happen.
The idea
Loop: sum = a ^ b; carry = (a & b) << 1; repeat until carry is 0 (mask to 32 bits for negative numbers).
Target: O(32) time
Go function shape
func getSum(a int, b int) intReference solution
Tested with go test. Try it yourself first, then compare.
// GetSum: add without + or -. XOR is addition without carry, AND shows where the carries go.
func GetSum(a, b int32) int32 {
for b != 0 {
carry := uint32(a&b) << 1
a ^= b
b = int32(carry)
}
return a
}