을 사용하지 않고 이진 정수를 추가하면 + 또는 -를 사용하지 않고 두 개의 정수를 더할 수 있습니다.+ 또는 -
이것은 내 해결책입니다.
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.
다른 사람들의 작업 솔루션을 옆에 그것을 측면을 비교, 그는이 있습니다 bascially 동일
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 음수라면 또 다른 음수를 얻습니다. – technosaurus