[LeetCode] Sum of Two Integers
2016-09-10 21:47
375 查看
The code is as follows.
The above code may be rewritten to make it more readable.
public class Solution { public int getSum(int a, int b) { return b == 0 ? a : getSum(a ^ b, (a & b) << 1); } }
The above code may be rewritten to make it more readable.
public class Solution { public int getSum(int a, int b) { while (b != 0) { int c = ((a & b) << 1); a ^= b; b = c; } return a; } }
cstands for the carry bit of adding two integers. The sum of two integers can be decomposed into a summation bit (
a & b) and a carry bit (
a ^ b). The
<< 1is to set the carry bit to the correct bit. The above process is repeated until no carry (
c, stored in
b, becomes 0). Then the sum is stored in
a.
相关文章推荐
- LeetCode 371: Sum of Two Integers 题解
- [leetcode-371]Sum of Two Integers(java)
- LeetCode:Sum of Two Integers
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- leetcode NO.371 sum of two integers
- [LeetCode] Sum of Two Integers 两数之和
- LeetCode:Sum of Two Integers
- leetcode:bits:Sum of Two Integers(371)
- [LeetCode]Sum of Two Integers
- leetcode371-----Sum of Two Integers
- LeetCode 371 Sum of Two Integers
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- Leetcode-Sum of Two Integers
- leetcode 371 Sum of Two Integers java实现
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- #leetcode#Sum of Two Integers
- LeetCode 第 371 题 (Sum of Two Integers)
- leetcode Sum of Two Integers
- LeetCode[371] Sum of Two Integers
- leetcode--sum of two integers