为什么另外这款code(使用位运算)的作品在Java中 [英] Why this code for addition(using bitwise operation) works in java
问题描述
public int add(int a, int b){
while (b != 0){
int carry = (a & b) ;
a = a ^ b;
b = carry << 1;
}
return a;
}
这是code来计算使用按位运算两个整数的总和。
This is the code to calculate sum of two integers using bitwise operation.
如果我手动/编程计算,我看到它为每一个整数。
但我无法弄清楚 A
和执行
的中间值之间的关系。
为什么进位乘以2指派给 B
?
If i calculate manually/programmatically, i see it works for every integer.
But i am not able to figure out any relation between intermediate value of a
and carry
.
and why carry is multiplied by 2 to assign to b
?
PS:我找到了一个答案在这里
按位乘法和加法在Java中
但是这是乘法而不是加法
PS: I found the one answer here Bitwise Multiply and Add in Java but this is for multiplication and not for addition.
推荐答案
先来回顾一下除了小学。例如26 + 147 = 173.您可以通过6 + 7 = 13开始,所以你把3的总和,并携带一个,等等 - 那就是:增加了两个数字,如果有必要
First recall addition in primary school. e.g. 26 + 147 = 173. You start by 6+7=13, so you put 3 in the sum, and carry the one, and so forth - that is: you add two digits and carry a one if necessary.
carry: 1
a: 26
b: 147
-----------------
sum: 173
在code确实对二进制数几乎同样的事情,但有一个小调整。而不是采取一个数字位置的时间,它需要所有一气呵成。代替包括i。从位置i-1的进位(即,包括1加入2和4时),则code添加所有龋在第二次迭代。那么,它的作用是: 026 + 147 = 163 + 010 = 173 + 000
有关二进制数字的= 6 = 00110以及b = 7 = 00101你
For the binary numbers a=6=00110 and b=7=00101 you get
首先,你发现携带;这是所有职位,其中两个 A
和 B
有其位设置: INT携带=( A和b);
First you find the carries; that is all positions where both a
and b
has its bit set: int carry = (a & b) ;
然后ID不会在另外的数字,忽略进位,并将其存储 A
: A = A ^ B;
这将响应 6 + 7 = 3
中的例子。
Then id does the addition of digits, ignoring the carry, and stores it in a
: a = a ^ b;
This will respond to 6+7=3
in the example.
最后一部分转移进到下一个数字位置,即确保在本例中的1搭载的是感动,从1对10的:携带和LT;&LT; 1;
The last part shifts the carry to the next digit position, i.e. ensuring the 1-carry in the example is "moved" from the 1's to the 10's: carry << 1;
while循环继续只要有携带尚未列入总和。
The while loop continues as long as there are carries that has not been included in the sum.
这篇关于为什么另外这款code(使用位运算)的作品在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!