python 解决lintcode a+b 超时问题

题目描述

lintcode a+b 问题

题目来源及自己的思路

https://www.lintcode.com/prob...

代码

def aplusb(self, a, b):
    # write your code here
    while True:
        a, b = a^b, (a&b)<<1
        if a==0 or b == 0:            return a or b

当 a=-b 时 为什么代码会超时, 而同样的逻辑,用Java就不会超时

  public int aplusb(int a ,int b) {        // write your code here, try to do it without arithmetic operators.
        while(true){        int x = a^b;  //记录不进位数
        int y = (a&b)<<1;  //记录进位数
        if(x==0){            return y;
        }        if (y==0){            return x;
        }
        a=x;
        b=y;
        } // while
            
        }


皈依舞
浏览 866回答 2
2回答

跃然一笑

原码、反码和补码咱整形数据以八位二进制为例那用整数5举个例子吧:原码: 0000 0101反码: 1111 1010补码: 1111 1011而补码就是负数在计算机中的二进制表示方法移位操作<<和>>简单的说就是向左或向右移动指定的位数, 空缺用0或1来补, 溢出的部分将被舍弃
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python