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.