371. Sum of Two Integers--LeetCode Record

Tong_hdj發表於2016-07-07

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example: Given a = 1 and b = 2, return 3.

抓住了一些運算子的特性,題目不難
class Solution {
    func getSum(a: Int, _ b: Int) -> Int {
        var xor = a ^ b
        var and = a & b
        and = and << 1
        if xor & and != 0 {
            return getSum(xor, and)
        }
        return xor | and
    }
}

相關文章