剑指offer——面试题47:不用加减乘除做加法

剑指offer——面试题47:不用加减乘除做加法

Solution1:

学习之
书上的思路就很好啊~

class Solution {
public:
    int Add(int num1, int num2) {
        int sum, carry;
        do {
            sum = num1 ^ num2;
            carry = (num1 & num2) << 1;

            num1 = sum;
            num2 = carry;
        } while(num2 != 0);
        return num1;
    }
};

Solution2:

20180910日重做。

class Solution {
public:
    int Add(int num1, int num2) {
        int res = 0, carry = 0;
        res = num1^num2;
        carry = (num1&num2) << 1;
        while (carry) {
            int tmp = res;
            res = res^carry;
            carry = (tmp&carry) << 1;
        }
        return res;
    }
};

你可能感兴趣的:(剑指offer题目笔记)