整数加法
371. Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example 1:
1 | Input: a = 1, b = 2 |
使用++ 和 – 运算
1 | public int getSum(int a, int b) { |
使用位运算
原理:二进制加法器
| x | y | sum | carry |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 0 | 1 | 1 | 0 |
| 1 | 0 | 1 | 0 |
| 1 | 1 | 0 | 1 |
进位的计算放好方式为 x 与 y
和的计算方式为 x 异或 y
1 | public int getSum(int a, int b) { |
回顾Java的位运算符
| 运算 | 运算符 | Demo |
|---|---|---|
| << | 左移 | 5<<2 = 20 左移2位 |
| >> | 右移 | 5>>2 = 1 右移2位 |
| >>> | 无符号右移 | -5>>>3 = 536870911 |
| & | 位与 | 5&3 = 1 |
| | | 位或 | 5 | 3 = 7 |
| ~ | 非 | ~5 = 6 |
| ^ | 异或 | 5^3 = 6 |