添加兩個整數。在不使用+或 - 的情況下添加二進制整數而不使用+或 -
這是我的解決方案。
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;
}
};
這是bascially相同。爲什麼我的解決方案不起作用?
因爲你的錯。這些操作的順序和位置非常重要。 –
我知道我錯了。但代碼基本相同 –
,因爲'while(temp> 0)'...如果你有'&'2負數,你會得到另一個負數 – technosaurus