版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ChiBaoNeLiuLiuNi/article/details/52240717
Calculate the sum of two integers a and b, but you are not allowed to use the operator +
and -
.
Example:
Given a = 1 and b = 2, return 3.
=================================
不让用加减符号,很自然想到用位运算,异或运算相同得零,不同得一,和加法很接近了,但是有个进位的问题。
// a 0 0 1 1
// b 0 1 0 1
// a ^ b 0 1 1 0
// a & b 0 0 0 1
而与运算刚好可以筛选出需要进位的情况,将其左移一位则得到应该有的进位,然后再令进位与 异或得到的数字做加法,如此循环直到没有进位
public class Solution {
public int getSum(int a, int b) {
while(b != 0){
int carry = a & b;
a = a ^ b;
b = carry<<1;
}
return a;
}
}
时间复杂度O(1),因为数字有多少个位是固定的