我想解决一个老问题:Write a function that add two [integer] numbers A and B. You should not use + or any arithmetic operators.For a + b in any base, we can treat the plus as two part: 1. a + b without carry; 2. the carry generated by a +b. The a+b then equals to part 1 plus part 2. If part1+part2 generates more carry, we can then repeat this procedure, until there is no carry.
我能理解这个算法,而且一切看起来都很好,所以我在lintcode上用下面粘贴的代码测试了它。class Solution:
"""
@param a: The first integer
@param b: The second integer
@return: The sum of a and b
"""
def aplusb(self, a, b):
while b != 0:
carry = a & b
a = a ^ b
b = carry << 1
return a
但令人惊讶的是,它在测试用例中给了我Time Limit Exceeded错误。所以我在本地运行它并为每个循环打印a,b:(-8, 8)
(-16, 16)
(-32, 32)
(-64, 64)
(-128, 128)
(-256, 256)
(-512, 512)
(-1024, 1024)
(-2048, 2048)
(-4096, 4096)
(-8192, 8192)
(-16384, 16384)
(-32768, 32768)
(-65536, 65536)
(-131072, 131072)
...
计算是正确的,所以我认为这种算法对于这样的输入不起作用,但是当我在C++中写同样的算法时,它只是工作:class Solution {
public:
int aplusb(int a, int b) {
while (b!=0){
int carry = a & b;
a = a^b;
b = carry << 1;
}
return a;
}
};
我不知道该问什么,基本上问题是:如果我使用Python,如何修改该算法使其工作?