题目
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.
分析
考察位运算,不用+ - 计算两数之和。
代码
/*
371. Sum of Two Integers
*/
#include <iostream>
#include <cstdlib>
using namespace std;
class Solution {
public:
//递归解决
int getSum1(int a, int b)
{
if (a != 0 && b != 0)
{
return getSum(a^b, (a&b) << 1);
}
else {
return a | b;
}//else
}
//非递归
int getSum(int a, int b) {
if (a != 0 && b != 0)
{
int sum = a;
while (b != 0)
{
sum = a ^ b;
b = (a & b) << 1;
a = sum;
}//while
return sum;
}
else {
return a | b;
}//else
}
};
int main()
{
cout << Solution().getSum(10, 11) << endl;
system("pause");
return 0;
}