Sum of Two Integers

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example:
Given a = 1 and b = 2, return 3.

我自己做的话只考虑了正数的情况,没有考虑负数,就按照查表的方法,列出0,0;0,1;1,0;1,1 还有进位情况,然后根据情况进行更新。代码如下

class Solution {
public:
    int getSum(int a, int b) {
    int c = 0, d = 0;
    int temp = 1;
    int mark = 0;
    int result = 0;
    int count = 0;
    int count1 = 0;
    c = a;
    d = b;
    while (c >>= 1) 
        count++;
    while (d >>= 1) count1++;
    if (count < count1) count = count1;

    for (int i = 0; i<=count+1;i++)
    {
        c=(a&temp)>>i;
        d = (b&temp)>>i;
        if (c != d)
        {

            if (mark == 0)
            { 
                mark = 0;
                result = result | (1 << i);
            }
            else
            {
                mark = 1;
                result = result | (0 << i);
            }
        }
        else
        {
            if (mark==0)
                result = result | (0 << i);
            else
                result = result | (1 << i);
            if ((c == 0) && (d == 0))
                mark = 0;
            if ((c == 1) && (d == 1))
                mark = 1;
        }

        temp=temp << 1;

    }
    return result;

    }
};

情况自然是不能ac的,所以参考了别人的做法。

class Solution {
public:
    int getSum(int a, int b) {
        int sum=a;
        while(b!=0)
        {
            sum=a^b;
            b=(a&b)<<1;
            a=sum;
        }
        return a;
    }
};

可以看出,异或在这里起到的作用是不考虑进位的加法,与操作起到的作用是找到所有1 与 1 对应的地方,以此为进位。直到进位表示数b为0为止.
就是说先用“抑或”考虑不进位的情况,然后用“与”考虑进位。然后再用抑或考虑进位的数,直到所有的进位都为0.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值