思路
模拟二进制计算
1.先转化为2个二进制数
2.二进制数相加,因为加法结合律 (a + b) + c = a + (b + c) 推出 a + b = (a - c) + (b - d) + (c + d)
3.采用^ 和 & 来获得两个数的 相加不进位的结果(a ^ b) 和 只进位的结果((a & b) << 1)
4.结合2和3,通过拆分数字可以得到 a + b = (a 相加不进位 b) + (a 只进位 b) = (a ^ b) + ((a & b) << 1)
^
0 0 = 0
0 1 = 1
1 0 = 1
1 1 = 0
&
0 0 = 0
0 1 = 0
1 0 = 0
1 1 = 1
eg:
2 + 3 = 5
0 0 1 0
0 0 1 1
-------
0 1 0 1
2 ^ 3 = 0 0 0 1 = 1
2 & 3 = 0 0 1 0 = 2 (向左进一位,加法进位)
2 + 3 = 1 + 4
0 0 0 1
0 1 0 0
-------
0 1 0 1
1 ^ 4 = 0 1 0 1 = 5
1 & 4 = 0 0 0 0 = 0
1 + 4 = 0 + 5
plus(2, 3) = plus(2 ^ 3, (2 & 3) << 1) = plus(1, 4)
plus(1 ,4) = plus(5, 0)
递归,确定递归出口
Python
class Solution:
"""
@param: : An integer
@param: : An integer
@return: The sum of a and b
"""
def aplusb(self, a, b):
# write your code here
# 递归
# return a if not b else aplusb(a ^ b, (a & b) << 1)
# 循环
import ctypes
while b:
tmp = ctypes.c_int32(a & b).value << 1
res = a ^ b
a = res
b = tmp
else:
return a
if __name__ == '__main__':
s = Solution()
print(s.aplusb(8, -4))
Go
package main
import "fmt"
/**
* @param a: An integer
* @param b: An integer
* @return: The sum of a and b
*/
func aplusb(a int, b int) int {
// write your code here
for {
if b == 0 {
return a
} else {
return aplusb(a^b, (a&b)<<1)
}
}
}
func main() {
fmt.Println(aplusb(2, 4))
fmt.Println(aplusb(3, 5))
}