首页 > 代码库 > [LeetCode] Sum of Two Integers
[LeetCode] Sum of Two Integers
The code is as follows.
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; }}
c
stands 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 << 1
is 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] Sum of Two Integers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。