Problem overview
The method getSum(_ a: Int, _ b: Int) -> Int receives two integers between -1000 and 1000 and returns their sum without using the operators + and -. The tools are the bitwise operators.
getSum(1, 2) returns 3. getSum(2, 3) returns 5. getSum(-5, 3) returns -2: negative numbers are stored in two's complement, and the same column-by-column addition works for them.
The lesson asks for O(1) time and O(1) extra space. The loop may run once per bit of the integer type, but no more.
Approach: add the columns, then add the carries
Think of adding two binary numbers on paper, one column at a time. In one column, 0 + 0 is 0, 0 + 1 is 1, and 1 + 1 is 10: a 0 stays in that column and a 1 is carried into the next one on the left.
- The digit left in each column is the XOR of the two bits:
x ^ y. This is the sum with all the carries left out. - A carry appears only in columns where both bits are 1: that is
x & y. It belongs one column to the left, so the carries are(x & y) << 1.
The two numbers, x ^ y and the shifted carries, still add up to x + y. So repeat the same step with them: XOR them, compute the new carries, and continue until no carry is left. Then the whole sum is in the XOR part.
Each round moves the lowest carry at least one place to the left. A Swift Int has 64 bits, so after at most 64 rounds the carries fall off the left end and become 0. The number of rounds doesn't grow with the size of the input.
Step by step
- Copy the parameters into
var x = aandvar y = b, since Swift parameters are constants.xholds the sum so far andythe carries still to add. - Loop while
y != 0. With no carries left, nothing more needs adding. - Compute the carries into
let carry = (x & y) << 1. This has to happen beforexchanges. - Add without carrying:
x = x ^ y. - Make the carries the next number to add:
y = carry. - Return
x.
The solution in Swift
class Solution {
func getSum(_ a: Int, _ b: Int) -> Int {
var x = a
var y = b
while y != 0 {
let carry = (x & y) << 1
x = x ^ y
y = carry
}
return x
}
}
The Swift details worth a closer look:
- Constant parameters. The loop changes both numbers, so they are copied into
vars first. - Shifts don't trap. Ordinary arithmetic on
Intthat overflows crashes the program in Swift, but<<simply discards the bits that move past the left end:Int.max << 1is-2. That is why the carry can fall off the end and become 0 instead of crashing. - Two's complement. A negative
Inthas its upper bits set, and nothing in the loop treats the sign specially. let carry. The carry is computed once per round and never changes, soletfits.
Tracing two additions
For getSum(2, 3), the state of x and y after each turn of the loop:
turn 1: x=1 y=4
turn 2: x=5 y=0
In binary, 010 + 011 first gives 001 with a carry of 100, and adding those leaves no further carry. The result is 5.
For getSum(-5, 3):
turn 1: x=-8 y=6
turn 2: x=-2 y=0
The result is -2, the right answer, with no special handling of the sign.
Complexity
Time: O(1). Each round pushes the carries at least one place left, and an Int has 64 bits, so the loop runs at most 64 times whatever the values are.
Space: O(1). Only x, y and carry are stored.
Edge cases and common mistakes
- One number is 0.
getSum(5, 0)returns 5 at once, becauseyis already 0. - Opposite numbers.
getSum(7, -7)returns 0.getSum(-1, 1)also returns 0, and it is the slow case: the carry travels through all 64 columns, so the loop runs 64 times. - Two negatives.
getSum(-1000, -1000)returns -2000. - Forgetting the shift. A carry belongs in the next column to the left. Using
x & ywithout<< 1adds it in the wrong place. - Updating
xbefore computing the carry. Afterx = x ^ y, the valuex & yis different. Computecarryfirst. - Using
+or-anywhere. The task forbids them, includingx - 1ory += carry.
Testing
a = 1,b = 2gives3.a = 2,b = 3gives5.a = -5,b = 3gives-2.a = 1000,b = -1000gives0.a = -1000,b = -1000gives-2000.a = 5,b = 0gives5.
