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.
Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
手写全加器,写出真值表达式。
注意的是最好用64位的bitset。32位会报错。
代码:
class Solution {
public:
int getSum(int a, int b) {
bitset<64> sum;
int index=0;
int temp=0;
int len=64;
int i=0;
while(len-->0)
{
sum[i++]=((a^b)&1)^index;
index=(a&b&1)|(index&((a^b)&1));
a=a>>1;
b=b>>1;
}
return sum.to_ulong();
}
};