模拟位运算解法1:
模拟位运算解法2:
class Solution {
public:
int add(int a, int b) {
uint32_t mask = 1;
bool lastCarry = false;
bool curCarry = false;
int result = 0;
uint32_t curPosAndResult;
uint32_t curPosOrResult;
for(int i = 0 ; i < 32 ; ++ i)
{
curPosAndResult = (a & mask) & (b & mask);
curPosOrResult = (a & mask) | (b & mask);
curCarry = curPosAndResult;
if(curCarry && lastCarry)
{
result |= mask;
}
else if(!curCarry && !lastCarry)
{
result |= curPosOrResult;
}
else if(curCarry && !lastCarry)
{
result &= ~mask;
}
else{
if(curPosOrResult){
curCarry = true;
result &= ~mask;
}else
{
result |= mask;
}
}
lastCarry = curCarry;
mask = mask << 1;
}
return result;
}
};