码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Sum of Two Integers

时间:2016-09-10 22:14:58      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/5860375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!