劍指offer 65. 不用加減乘除作加法(Leetcode 371. Sum of Two Integers)

劍指offer 65. 不用加減乘除作加法(Leetcode 371. Sum of Two Integers)函數

https://leetcode.com/problems/sum-of-two-integers/spa

題目:code

寫一個函數,求兩個整數之和,要求在函數體內不得使用加減乘除這四個符號。blog

分析:leetcode

對於不能使用正常的四則運算符,通常就是使用位運算了。而本題要想實現加法,只能使用異或了。get

須要注意的是,加法的時候涉及進位,而進位的實現利用與運算class

此外,進位以後還有可能產生進位,因此要在循環裏實現。循環

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;
}

總結:二進制

本題雖然是一道easy題,且寥寥幾行代碼,但從思路到實現,實際上是很巧妙的,也不是說很容易就寫這麼完美。好比將sum賦予num1,carry賦予num2。總結

相關文章
相關標籤/搜索