写一个函数,求两个整数之和,要求不得使用 +、-、*、/ 四则运算符号。
解题思路
class Solution:
def Add(self, num1, num2):
# write code here
return sum([num1,num2])
a ^ b 表示没有考虑进位的情况下两数的和,(a & b) << 1 就是进位。
递归会终止的原因是 (a & b) << 1 最右边会多一个 0,那么继续递归,进位最右边的 0 会慢慢增多,最后进位会变为 0,递归终止。
python中负数的二进制编码比较特殊
# 可以处理整数的加法,但不能处理负数
class Solution:
def Add(self, num1, num2):
# write code here
return num1 if num2 == 0 \
else self.Add(num1 ^ num2, (num1 & num2) << 1)
可以用 ctypes 来在 Python 中定义 C 语言的数据类型:
class Solution:
def Add(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
import ctypes
a = ctypes.c_int32(a).value
b = ctypes.c_int32(b).value
while b != 0:
carry = ctypes.c_int32(a & b).value
a = ctypes.c_int32(a ^ b).value
b = ctypes.c_int32(carry << 1).value
return a