python如何求a和b的和_没有算术运算符的A+B,Python与C++

我想解决一个老问题: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,如何修改该算法使其工作?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值