371. Sum of Two Integers
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
分析
加法运算不能用+和-符号,自然可以想到位运算。
^:异或运算符,实现两个数不考虑进位的加法
&,<<:与运算,位移运算,两个共同实现进位操作
当不需要进位时,加法就算完了,这时退出循环。
代码
#include<iostream>
using namespace std;
class Solution {
public:
int getSum(int a, int b) {
int sum;
while (b != 0) {
sum = a ^ b;
b = (a & b) << 1;
a = sum;
}
return sum;
}
};
int main() {
Solution s;
printf("11 + 89 = %d\n",s.getSum(11, 89));
return 0;
}
复杂度分析
时间复杂度 | 空间复杂度 |
---|---|
O(n) | O(1) |