如何使用按位运算添加两个整数的同时为无限循环添加代码修复 [英] How to add a code fix for infinite loop while adding two integers using bitwise operations

查看:99
本文介绍了如何使用按位运算添加两个整数的同时为无限循环添加代码修复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是原始的问题.

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

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.

推荐答案

我假设您已经了解了无限循环背后的逻辑. 逻辑

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

以下是程序的行为:

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

这篇关于如何使用按位运算添加两个整数的同时为无限循环添加代码修复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆