问题描述:
Calculate the sum of two integers a and b, but you are not allowed to use the operator +
and -
.
示例:
Given a = 1 and b = 2, return 3.
问题分析:
不用+和-,我们可以考虑从位运算的角度出发。主要用到了进位操作和异或运算.
过程详见代码:
class Solution {
public:
int getSum(int a, int b) {
int res = a ^ b;
int flag = 0;
int jin = 0;
int i = 1,j = 1;
while(i++ <= 32)
{
jin = jin ^ flag;
flag = ((a & b & j) | (a & flag) | (b & flag));
flag <<= 1;
j <<= 1;
}
return (res ^ jin);
}
};