Leetcode的一道题
在二进制条件下,异或可以实现没有进位的求和。而进位可以通过按位与&来实现。
class Solution {
func getSum(_ a: Int, _ b: Int) -> Int {
//change let to var for operation
var (x, y) = (a, b)
repeat {
let carry = x & y
x = x ^ y
y = carry << 1
} while y != 0
return x
}
}
网友评论