は、+または - を使用せずに2つの整数を加算します。+または - を使用しないバイナリ整数の追加
これは私のソリューションです。
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;
}
};
しかし、それはケースに動作しない場合= -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