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.
class Solution {
public:
int getSum(int a, int b) {
int carry = 0, num = 0, bita, bitb;
for(int i = 0; i < 32; ++i)
{
bita = a & (1<<i);
bitb = b & (1<<i);
carry = (carry<<i);
num |= bita ^ bitb ^ carry;
if((bita & bitb) || (bita & carry) || (bitb & carry))
carry = 1;
else
carry = 0;
}
return num;
}
};
本文介绍了一种特殊的算法实现方式,即如何在不使用加法和减法运算符的情况下计算两个整数的和。通过位操作实现了这一目标,展示了位运算的独特魅力。
756

被折叠的 条评论
为什么被折叠?



