Java 不使用+;添加两个数字背后的实现逻辑;?

Java 不使用+;添加两个数字背后的实现逻辑;?,java,add,Java,Add,我在网上找到了这个代码。但是,我无法获得以下代码背后的逻辑: public static int add(int a, int b) { if (b == 0) return a; int sum = a ^ b; // add without carrying System.out.println("sum is : "+sum); int carry = (a & b) << 1; // carry, but don’t add r

我在网上找到了这个代码。但是,我无法获得以下代码背后的逻辑:

public static int add(int a, int b) {
    if (b == 0) return a;
    int sum = a ^ b; // add without carrying
    System.out.println("sum is : "+sum);
    int carry = (a & b) << 1; // carry, but don’t add
    return add(sum, carry); // recurse
}
publicstaticintadd(inta,intb){
如果(b==0),则返回a;
int sum=a^b;//不带进位的加法
System.out.println(“总和为:“+sum”);

int carry=(a&b)我们正在添加将整数转换为位并使用逐位运算符

EXOR即^:0^0和1^1=0,其他情况下为1

也就是&1^1=1,…其他情况下为0

让我们看一个例子(为了简单起见,使用8位)

a^b
是异或,对于一个数字中有
1
而另一个数字中有
0
的位置,它给出
1
。在我们的示例中:

a^b = 10101011
由于
0+0=0
0+1=1
1+0=1
,所以只剩下在这两个数字中都有
1
的列了。在我们的示例中,
a^b
无论答案是什么,都是短的

      00010100
    + 00010100
在二进制中,
1+1=10
,因此上述总和的答案为

      00101000

(a&b)这是添加的表格:

+   0  1
   -- --
0 | 0  1
1 | 1 10
      ▲
如果忽略进位
您将看到它与XOR表相同:

^   0  1
   -- --
0 | 0  1
1 | 1  0
所以,如果你将两个数字按位异或组合,你可以得到不带进位的逐位加法

现在,进位是什么?只有当两个输入都是1时,进位才存在

您可以通过以下方式获得:

&   0  1
   -- --
0 | 0  0
1 | 0  1

但它需要在向左移动一个位置后添加到总和中,因为它是“结转”的,因此
(a&b)考虑,例如,
5+7

5     = 101 (Base 2)
7     = 111 (Base 2)

现在考虑添加两个(基2)数字:

A+B
的和(不带进位)为
A^B
,进位为
A&B
;当您携带一个数字时,它会向左移动一位(因此
(A&B))
&   0  1
   -- --
0 | 0  0
1 | 0  1
5     = 101 (Base 2)
7     = 111 (Base 2)
0+0 =  0 = 0 carry 0
1+0 =  1 = 1 carry 0
0+1 =  1 = 1 carry 0
1+1 = 10 = 0 carry 1
5    =  101 (Base 2)
7    =  111 (Base 2)
5^7  =  010 (sum without carrying)
5&7  = 101  (the carry shifted left)
A    =   010
B    =  1010
A^B  =  1000 (sum without carrying)
A&B  = 0010  (the carry shifted left)
A'    =  1000
B'    =   100 (without the leading zeros)
A'^B' =  1100 (sum without carrying)
A'&B' = 0000  (the carry shifted left)