Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};
posted on 2015-09-13 13:00  Tonix  阅读(155)  评论(0编辑  收藏  举报