#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
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.
分析:不允许使用加减号来求两个数的和。设置一个类,里面
存放一个静态计数器,实例化之后,每次调用一次,累加计数器。
或者位操作,求出两数相加的时候,先不进位的值val1,和单独求出进位的部分val2
然后进行val1与val2进行加操作。
举例
3 5
3: 0011
5: 0101
单独累加不进位,就是异或运算得到3^5=0110=6
单独进位运算,两个都是1才进位:0010=2(如果两个数字第i位都是1,进位为1 << (i+1),要向左多移动一维)
6+2,不对。
0110
0010
再次求carry和以后结果
还是位操作,做一些判断而已
进位只有:bit1,bit2,carry中至少两个为1
输入:
1 2
1 -2
1 -1
输出:
3
-1
0
关键:
1 记住,不允许使用符号计算结果,采用位运算。注意:carry = a & b , a = a ^ b,b = carry << 1
把a视作单独计算不进位的结果,把b视作单独进位不计算的结果,直到进位b为0,即可
*/
class Solution {
public:
int count(int bit1 , int bit2 , int carry)
{
int num = 0;
if(0 != bit1)
{
num++;
}
if(0 != bit2)
{
num++;
}
if(1 == carry)
{
num++;
}
return num;
}
int getSum2(int a, int b) {
int result = 0;
int carry = 0;
//两个数不断向右移动即可
int i = 0;
int mask;
for( i = 0 ; i < 32 ; i++)
{
mask = (1 << i);
int bit1 = mask & a;
int bit2 = mask & b;
int count1 = count(bit1 , bit2 ,carry);
int curBit = count1 % 2;
carry = count1 / 2;
result |= (curBit << i);
}
return result;
}
//注意:carry = a & b , a = a ^ b,b = carry << 1
//把a视作单独计算不进位的结果,把b视作单独进位不计算的结果,直到进位b为0,即可
int getSum(int a, int b) {
int carry = 0;
while(b != 0)
{
carry = a & b;//求单独进位
a = a ^ b;//求单独计算结果
b = carry << 1;//进位左移一位
}
return a;
}
};
void process()
{
int a;
int b;
Solution solution;
int result;
while(cin >> a >> b )
{
result = solution.getSum(a , b);
cout << result << endl;
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}