题目描述:同点击打开链接
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
思路一:
class Solution {
public int getSum(int a, int b) {
while (b != 0)
{
int tmp = a ^ b;
b = (a & b) << 1;
a = tmp;
}
return a;
}
}
class Solution {
public int getSum(int a, int b) {
return b == 0 ? a : getSum(a ^ b, (a & b) << 1);
}
}
若为相减,则
class Solution {
public int getSubstract(int a, int b)
{
while (b != 0)
{
int tmp = a ^ b;
b = ((~a) & b) << 1;
a = tmp;
}
return a;
}
}
class Solution {
public int getSubstract(int a, int b)
{
return b == 0 ? a : getSubstract(a ^ b, ((~a) & b) << 1);
}
}
总结:
点击打开链接