[Swift]LeetCode371. 两整数之和 | Sum of Two Integers
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9769295.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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.
Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.
不使用运算符 +
和 -
,计算两整数 a
、b
之和。
示例 1:
输入: a = 1, b = 2 输出: 3
示例 2:
输入: a = -2, b = 3 输出: 1
8ms
1 class Solution { 2 func getSum(_ a: Int, _ b: Int) -> Int { 3 //按位取异或 4 var res:Int = a^b 5 //判断是否需要进位 6 var forward = (a&b) << 1 7 if forward != 0 8 { 9 //如有进位,则将二进制数左移一位,进行递归 10 return getSum(res, forward) 11 } 12 return res 13 } 14 }
8ms
1 class Solution { 2 func getSum(_ a: Int, _ b: Int) -> Int { 3 if a == 0 { 4 return b 5 } 6 7 if b == 0 { 8 return a 9 } 10 11 var a = a 12 var b = b 13 while b != 0 { 14 let carry = a & b 15 a = a ^ b 16 b = carry << 1 17 } 18 return a 19 } 20 }
8ms
1 class Solution { 2 func getSum(_ a: Int, _ b: Int) -> Int { 3 if a&b==0 { 4 return a|b 5 } 6 return getSum(a^b, (a&b)<<1) 7 } 8 }
12ms
1 class Solution { 2 func getSum(_ a: Int, _ b: Int) -> Int { 3 var carry = (a & b) << 1 4 var result = a ^ b 5 while carry != 0 { 6 let carryTemp = carry 7 carry = (result & carryTemp) << 1 8 result = result ^ carryTemp 9 } 10 return result 11 } 12 }
16ms
1 class Solution { 2 func getSum(_ a: Int, _ b: Int) -> Int { 3 4 if b == 0 { 5 return a 6 } else { 7 return getSum(a ^ b, (a & b) << 1) 8 } 9 } 10 }