# 位运算实现加法

## 位运算实现加法

Posted by Jae on May 23, 2019

1 + 1 = 0 向上进了一个1
1 + 0 = 1
0 + 1 = 1
0 + 0 = 0


1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0


0 + 0 = 0
1 + 0 = 0
0 + 1 = 0
1 + 1 = 1

0 & 0 = 0
1 & 0 = 0
0 & 1 = 0
1 & 1 = 1


(x & y) << 1


x ^ y 加法
(x & y) << 1 进位


Java实现

public int getSum(int a, int b) {
int jw = a & b;
int jg = a ^ b;
while (jw != 0){
int t_a = jg;
int t_b = jw << 1; // 进位
jw = t_a & t_b;
jg = t_a ^ t_b;
}
return jg;
}