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

LintCode "A + B Problem"

时间:2015-09-13 13:17:42      阅读:189      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!