Sum of Two Integers【不用+ -,算加法】

PROBLEM:

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

SOLVE:

class Solution {
public:
    int getSum(int a, int b) {
        long long sum=a;
        while(b!=0){
            sum=a^b;
            b=(a&b)<<1;
            a=sum;
        }
        return sum;
    }
};
解释:不用加法,用位运算即可算出和,步骤浅显易懂!

猜你喜欢

转载自blog.csdn.net/sim0hayha/article/details/80146267
今日推荐