首页 > 其他 > 详细

LintCode "A + B Problem"

时间:2015-09-13 13:14:59      阅读:228      评论:0      收藏:0      [点我收藏+]

Using XOR on bits.

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) {
        int c = 0, carry = 0;
        for(int i = 0; i < 32; i ++)
        {
            char ba = (a >> i) & 0x1;
            char bb = (b >> i) & 0x1;
            char bc = ba ^ bb ^ carry;
            c |= bc << i;
            
            if ( (ba && bb) || (ba && carry) || (bb && carry))
                carry = 1;
            else 
                carry = 0;
        }
        return c;
    }
};

LintCode "A + B Problem"

原文:http://www.cnblogs.com/tonix/p/4804609.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!