题目描述:写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
import Foundation
class For47Solution {
func addSum(_ a: Int,_ b: Int) -> Int {
var n1 = a
var n2 = b
while n2 != 0 {
let sum = n1 ^ n2
let carry = (n1 & n2) << 1
n1 = sum
n2 = carry
}
return n1
}
}
算法思想:位运算模拟加法。
github地址:https://github.com/cubegao/LeetCode