[easy]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:Given a = 1 and b = 2, return 3.

这道题目考查了加法的实现方法,由于我真值表达式不太记得怎么写,我根据规律写出了如下式子:

sum = digit1 ^ digit2 ^ carry;
carry = digit1 ^ digit2 ? carry ? digit1 & digit2;
class Solution {
public:
    int getSum(int a, int b) {
        while(b)
        {
            int c = a^b;
            b = (a&b)<<1;
            a = c;
        }
        return a;
    }
};

你可能感兴趣的:([easy]371. Sum of Two Integers)