Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example 1:
Input: a = 1, b = 2 Output: 3
Example 2:
Input: a = -2, b = 3 Output: 1
//不能使用 + -
public static int getSum(int a, int b) {
return b==0? a:getSum(a^b, (a&b)<<1);
}
public static int getSum2(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;
}
git:https://github.com/woshiyexinjie/leetcode-xin
本文介绍了一种在不使用加号和减号的情况下,实现两个整数相加的方法。通过位运算中的异或和与操作,结合左移运算符,巧妙地实现了加法功能,提供了一个有趣且实用的编程技巧。

756

被折叠的 条评论
为什么被折叠?



