描述
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.
分析
「not allowed to use the operator +
and -
.」,这就尴尬了,偷偷用了一下 +
号,还是可以通过的,
这里要用位运算实现加法,首先,有一个这样的公式,a+b = a^b + (a&b)<<1
,怎么理解呢,其实可以从加法的运算思路这个角度来思考,a^b
是不考虑进位时加法结果,而(a&b)<<1
是产生的进位的值,即进位补偿,这样两者相加的话便是完整加法的结果。而 a^b
和 (a&b)<<1
这样的运算是可能出现 0 的情况的,这样的话我们可以写一个这样的函数:
1 | def add(a, b): |
当然,这个函数是有限制的,具体表现在,如果 a,b 为一正一负的话,那么计算的结果一定是负数,因此,限制是这样的:
a*b>0
a*b<0
假设a<0
,那么abs(a)>b>0
怎么满足这个限制呢?现在假设一种不满足上述条件的情况,a<0
,且b>abs(a)>0
,那么 a+b
可以写为 -add(-a, -b),这个求反的行为怎么实现?其实可以从补码的角度考虑,求反加一即可,如 -a=add(~a, 1)
,搞清楚了这些,就可以写代码了
解决方案1(C++)
啦啦啦:
1 | class Solution { |
1 | class Solution { |
解决方案2(Python)
做个弊
1 | class Solution(object): |
正经解答:
1 | class Solution(object): |