P5 不用+/-求两数之和
算法 34 阅读
信号摘要
难度:Easy · 时长:05:50 · leetcode 371
未对外公开播放权限
点击查看说明
描述
这个题目说的是,给你两个整数,在不使用 +/- 这两个运算符的前提下,求它们的和。
代码
public class AlgoCasts {
public int getSumRecursive(int a, int b) {
return b == 0 ? a : getSumRecursive(a^b, (a&b)<<1);
}
// Time: O(m), Space: O(1)
public int getSumIterative(int a, int b) {
while (b != 0) {
int sum = a ^ b;
int carry = (a & b) << 1;
a = sum;
b = carry;
}
return a;
}
}