题目地址:
https://www.lintcode.com/problem/sum-of-two-integers/description
给定两个32位整数,求其和。不允许用加减法。
思路是位运算。参考https://blog.csdn.net/qq_46105170/article/details/104470821。代码如下:
public class Solution {
/**
* @param a:
* @param b:
* @return: return an integer
*/
public int getSum(int a, int b) {
// wirte your code here
int res = a;
while (b != 0) {
res = a ^ b;
b = (a & b) << 1;
a = res;
}
return res;
}
}
时空复杂度 O ( 1 ) O(1) O(1)。