[LintCode] A + B Problem

class Solution {
public:
    /*
     * @param a: The first integer
     * @param b: The second integer
     * @return: The sum of a and b
     */
    int aplusb(int a, int b) {
        // write your code here, try to do it without arithmetic operators.
        if (b == 0) 
            return a;
        else
        //sumWithoutCarry = a^b
        //carry = (a&b) << 1
        //sumWithoutCarry has to XOR till carry is 0
        //which means all the carry has been considered. 
            return aplusb(a^b, (a&b) << 1);
    }
};

这是一个bit opperation 的题目。 九章算法有一个比较好的解释 http://www.jiuzhang.com/solutions/a-b-problem/

a^b是不进位的加法,什么时候需要进位呢,就是a和b都是1的情况。这个时候a&b就能给出所有需要进位的位,所谓进位就是需要左移一位。a&b << 1就是进位的值,不进位加上进位就是a+b的值。什么时候停止呢,就是没有需要的进位了,即进位为0.

/**
 * 本代码由九章算法编辑提供。没有版权欢迎转发。
 * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
 * - 现有的面试培训课程包括:九章算法班,系统设计班,九章强化班,Java入门与基础算法班,
 * - 更多详情请见官方网站:http://www.jiuzhang.com/
 */

class Solution {
    /*
     * param a: The first integer
     * param b: The second integer
     * return: The sum of a and b
     */
    public int aplusb(int a, int b) {
        // 主要利用异或运算来完成 
        // 异或运算有一个别名叫做:不进位加法
        // 那么a ^ b就是a和b相加之后,该进位的地方不进位的结果
        // 然后下面考虑哪些地方要进位,自然是a和b里都是1的地方
        // a & b就是a和b里都是1的那些位置,a & b << 1 就是进位
        // 之后的结果。所以:a + b = (a ^ b) + (a & b << 1)
        // 令a' = a ^ b, b' = (a & b) << 1
        // 可以知道,这个过程是在模拟加法的运算过程,进位不可能
        // 一直持续,所以b最终会变为0。因此重复做上述操作就可以
        // 求得a + b的值。
        while (b != 0) {
            int _a = a ^ b;
            int _b = (a & b) << 1;
            a = _a;
            b = _b;
        }
        return a;
    }
};

posted on 2016-07-05 08:14  codingEskimo  阅读(135)  评论(0编辑  收藏  举报

导航