How to add a code fix for infinite loop while adding two integers using bitwise operations

孤者浪人 提交于 2020-01-05 06:09:25

问题


Here is the original question.

Here is the code for adding two integers using bitwise operations:

def getSum(self, a, b):

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

    return a ^ b

Though I know the reason why it goes into an infinite loop while adding a positive and negative integer, I need some help with coming up with the code-fix for this.


回答1:


I am assuming that you have gone through the logic behind the infinite loop you are getting. logic

Following is the behaviour of your program :

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.`

So you will have to handle the fourth case explicitly. You may write a wrapper for it. Also you need one more utility to negate the value of a number i.e. if the number is positive make it negative and vice versa:

# 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


来源:https://stackoverflow.com/questions/40208208/how-to-add-a-code-fix-for-infinite-loop-while-adding-two-integers-using-bitwise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!