Python 如何在使用逐位运算添加两个整数时为无限循环添加代码修复

Python 如何在使用逐位运算添加两个整数时为无限循环添加代码修复,python,python-3.x,bit-manipulation,bitwise-operators,Python,Python 3.x,Bit Manipulation,Bitwise Operators,这是原件 以下是使用位运算添加两个整数的代码: def getSum(self, a, b): while (a & b): x = a & b y = a ^ b a = x << 1 b = y return a ^ b def getSum(self,a,b): 而(a&b): x=a&b y=a^b a=x我假设你已经经历了无限循环背后的逻辑 以下是您的程序的行为: 1. G

这是原件

以下是使用位运算添加两个整数的代码:

def getSum(self, a, b):

    while (a & b):
        x = a & b
        y = a ^ b
        a = x << 1
        b = y

    return a ^ b
def getSum(self,a,b):
而(a&b):
x=a&b
y=a^b

a=x我假设你已经经历了无限循环背后的逻辑

以下是您的程序的行为:

1. Gives correct result when both a and b are positive.

2. Gives correct result when both a and b are negative.

3. Gives correct result when one of them is positive and one of them is negative
   and positive one is smaller than negative one.

4. Gives incorrect result (infinite loop) when one of them is positive and one of 
   them is negative and positive one is bigger than negative one.`
因此,您必须明确地处理第四种情况。你可以为它写一个包装。此外,还需要另外一个实用程序来对数字的值求反,即,如果数字为正数,则将其设为负数,反之亦然:

# I will leave neagte(x) on you to implement.
# So assume we have  negate() method available.

def getSum(a,b):
     # if a is -ve and b is +ve and abs(a) is less than b.
     cond1 =  a < 0 and b > 0 and abs(a) < b

     # if b is -ve and a is +ve and abs(b) is less than a.
     cond2 =  b < 0 and a > 0 and abs(b) < a

     # if any of these conditions are met. negate the value of a and b 
     # and negate the value of answer as well.
     if cond1 or cond2:
         return negate(_getSum(negate(a),negate(b)))

     # otherwise run normally.
     return _getSum(a,b)


def _getSum(a, b):
     while (a):
         x = a & b
         y = a ^ b
         a = x << 1
         b = y
     return b
#我将把neagte(x)留给您来实现。
#所以假设我们有可用的negate()方法。
def getSum(a、b):
#如果a为-ve,b为+ve,abs(a)小于b。
cond1=a<0且b>0且abs(a)0且abs(b)