【发布时间】:2017-04-03 15:26:24
【问题描述】:
不使用 + 或 - 将两个整数相加。
这是我的解决方案。
class Solution {
public:
int getSum(int a, int b) {
int temp=a & b;
a=a^b;
while (temp>0){
b=temp<<1;
temp=a & b;
a=a^b;
}
return a;
}
};
但它不适用于 a=-12 的情况, b=-8。
将其与其他人的工作解决方案并列比较,他有:
class Solution {
public:
int getSum(int a, int b) {
int sum = a;
while (b != 0)
{
sum = a ^ b;//calculate sum of a and b without thinking the carry
b = (a & b) << 1;//calculate the carry
a = sum;//add sum(without carry) and carry
}
return sum;
}
};
基本上是一样的。为什么我的解决方案不起作用?
【问题讨论】:
-
因为你的错了。操作的顺序和位置很重要。
-
我知道我错了。但是代码基本一样
-
因为
while (temp>0)...如果你&2个负数,你会得到另一个负数 -
不,它们基本上不一样。再读一遍我写的,特别是第二句话。 abc 与背诵字母表时的 bac 或 cab 基本不同。
-
如果我将
while(temp<0)更改为while (temp != 0),你认为这会起作用吗?
标签: c++ binary bit-manipulation bit