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.
这道题就让我们看看大神们的方法吧!
public int getSum(int a, int b) {
if(b == 0){//没有进位的时候完成运算
return a;
}
int sum,carry;
sum = a^b;//完成第一步加法的运算
carry = (a&b)<<1;//完成第二步进位并且左移运算
return getSum(sum,carry);//
}
// Iterative
public int getSum(int a, int b) {
if (a == 0) return b;
if (b == 0) return a;
while (b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
// Iterative
public int getSubtract(int a, int b) {
while (b != 0) {
int borrow = (~a) & b;
a = a ^ b;
b = borrow << 1;
}
return a;
}
@Wayne3223 It depends whether 'a' is the minuend(被除数) or subtrahend(除数). i.e. difference = minuend - subtrahend.
If you write it as "2-3", and see 'a' as 3, and 'b' as 2. then the formula should be borrow = ((~a)+1) & b;
See an example here. When b becomes 0, a = -1. a = 3 b = 2
a = 0011 b = 0010
borrow = 1101 & 0010 = 0001 a = 0001 b = 0010
borrow = 1111 & 0010 = 0010 a = 0011 b = 0100
borrow = 1101 & 0100 = 0100 a = 0111 b = 1000
borrow = 1001 & 1000 = 1000 a = 1111 b = 0000
so a = -1;
However, if you write it as just "3 - 2", and take 'a' as 3 and 'b' as 2, then formula for borrow is borrow = (~a) & b;
See an example below. subtract 2 from 3. a = 3 b = 2
a = 0011 b = 0010
borrow = 1100 & 0010 = 0000 a = 0001 b = 0000
a = 1;
So I believe it depends on the position of a. If it is a - b then borrow = (~a) & b; else if it is b - a then borrow = ((~a)+1) & b; or (~b) & a; Honestly, I prefer the former one. Correct me if anything is wrong here.
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.这道题就让我们看看大神们的方法吧!public int getSum(int a, int b)