美文网首页
371. Sum of Two Integers (重)

371. Sum of Two Integers (重)

作者: 殷水臣 | 来源:发表于2017-02-21 15:43 被阅读0次

这是一道很棒的题,对位运算的理解十分有帮助,嗯,好好回忆对比计组里的加法。。。

我的解法

反正我还是没用+和-嘛QvQ

class Solution {
public:
    int getSum(int a, int b) {
        if (b >= 0){
            for (int i = 0; i < b; i ++)
            ++ a;    
        }else{
            for (int i = 0; i > b; i --)
            -- a; 
        }
        return a;
    }
};

人家的解法

好好学习一下,嗯。

class Solution {
public:
    int getSum(int a, int b) {
        int sum = a;
        
        while (b != 0)
        {
            sum = a ^ b;//calculate sum of a and b without thinking the carry 
            b = (a & b) << 1;//calculate the carry
            a = sum;//add sum(without carry) and carry
        }
        
        return sum;
    }
};

相关文章

网友评论

      本文标题:371. Sum of Two Integers (重)

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