美文网首页
Sum of two Integers

Sum of two Integers

作者: partrick | 来源:发表于2016-10-25 10:51 被阅读0次

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
    }
}

相关文章

网友评论

      本文标题:Sum of two Integers

      本文链接:https://www.haomeiwen.com/subject/scdruttx.html