美文网首页Leetcode
Leetcode.371.Sum of Two Integers

Leetcode.371.Sum of Two Integers

作者: Jimmy木 | 来源:发表于2019-12-31 11:43 被阅读0次

题目

不用加法计算加法。

Input:1,-1
Output: 0
Input:-1,10
Output: 9

思路

不使用加法就只能使用位运算。需要考虑负数的加法,减法和加法应该一样,采用取反加1的方式将减法改为加法。

int getSum(int a, int b) {
    unsigned int carry = 1;
    while (carry) {
        carry = a & b;
        a = a ^ b;
        b = carry << 1;
    }
    return a;
}

总结

位运算需要花时间去细细品味。
更多计算参考https://www.cnblogs.com/kiven-code/archive/2012/09/15/2686922.html

相关文章

网友评论

    本文标题:Leetcode.371.Sum of Two Integers

    本文链接:https://www.haomeiwen.com/subject/vlsboctx.html