题目描述:
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
解题思路1:
利用python内置sum即可
代码1:
class Solution:
def add(self, a, b):
L1 = [a, b]
return sum(L1)
解题思路2:
使用按位异或
和按位与
运算。计算a + b
等价于计算(a ^ b) + ((a & b) << 1)
,其中((a & b) << 1)
表示进位。因此令a等于(a & b) << 1
,令b等于a ^ b
,直到a变成0,然后返回b。
代码2:
class Solution:
def add(self, a, b):
while (a != 0):
temp = a ^ b
a = (a & b) << 1
b = temp
return b
题目来源:
https://leetcode-cn.com/problems/bu-yong-jia-jian-cheng-chu-zuo-jia-fa-lcof/