无限循环,同时在Python 3中使用按位运算添加两个整数 [英] Infinite loop while adding two integers using bitwise operations in Python 3

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

问题描述

我正在尝试使用python代码解决问题,这要求我添加两个整数而不使用'+'或'-'运算符.我有以下代码非常适合两个正数:

I am trying to solve a problem, using python code, which requires me to add two integers without the use of '+' or '-' operators. I have the following code which works perfectly for two positive numbers:

def getSum(self, a, b):

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

    return a ^ b

如果输入是两个正整数或两个负整数,则这段代码可以很好地工作,但是当一个数字为正数而另一个数字为负数时,此代码将失败.它进入无限循环.为什么会发生这种情况的任何想法?

This piece of code works perfectly if input is two positive integers or two negative integers but it fails when one number is positive and other is negative. It goes into infinite loop. Any idea as to why this might be happening?

这是

Here is the link discussing the code fix for this.

推荐答案

Python 3具有任意精度整数( "bignums").这意味着,任何时候x为负,x << 1都会使x为负数,幅度为两倍.零从右边移入只会将数字推得越来越大.

Python 3 has arbitrary-precision integers ("bignums"). This means that anytime x is negative, x << 1 will make x a negative number with twice the magnitude. Zeros shifting in from the right will just push the number larger and larger.

在二进制补码中,正数的最高位为0,负数的最高位为1.这意味着,当ab中只有一个为负时,ab的高位将不同.因此,x将为正(1 & 0 = 0),而y将为负(1 ^ 0 = 1).因此,新的a将为正(x<<1),而新的b将为负(y).

In two's complement, positive numbers have a 0 in the highest bit and negative numbers have a 1 in the highest bit. That means that, when only one of a and b is negative, the top bits of a and b will differ. Therefore, x will be positive (1 & 0 = 0) and y will be negative (1 ^ 0 = 1). Thus the new a will be positive (x<<1) and the new b will be negative (y).

现在:至少在数学上,任意精度的负整数实际上具有无限数量的前导1位.因此,a是一个越来越大的正数,每次迭代扩展2. b不断增加越来越多的前导1位,以便能够对a进行按位的&^.因此,a的任何位都与b的添加的1位之一对齐,因此a & b始终为真,因此循环永远运行.

Now: arbitrary-precision negative integers actually have an infinite number of leading 1 bits, at least mathematicallly. So a is a larger and larger positive number, expanding by 2 each iteration. b keeps getting more and more leading 1 bits added to be able to carry out the bitwise & and ^ with a. Thus whatever bits of a are turned on line up with one of the added 1 bits of b, so a & b is always true, so the loop runs forever.

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

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