C++實現LeetCode(29.兩數相除)

[LeetCode] 29. Divide Two Integers 兩數相除

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.

Example 1:

Input: dividend = 10, divisor = 3
Output: 3

Example 2:

Input: dividend = 7, divisor = -3
Output: -2

Note:

  • Both dividend and divisor will be 32-bit signed integers.
  • The divisor will never be 0.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

這道題讓我們求兩數相除,而且規定不能用乘法,除法和取餘操作,那麼這裡可以用另一神器位操作 Bit Manipulation,思路是,如果被除數大於或等於除數,則進行如下循環,定義變量t等於除數,定義計數p,當t的兩倍小於等於被除數時,進行如下循環,t擴大一倍,p擴大一倍,然後更新 res 和m。這道題的 OJ 給的一些 test case 非常的討厭,因為輸入的都是 int 型,比如被除數是 -2147483648,在 int 范圍內,當除數是  -1 時,結果就超出瞭 int 范圍,需要返回 INT_MAX,所以對於這種情況就在開始用 if 判定,將其和除數為0的情況放一起判定,返回 INT_MAX。然後還要根據被除數和除數的正負來確定返回值的正負,這裡采用長整型 long 來完成所有的計算,最後返回值乘以符號即可,代碼如下:

解法一:

class Solution {
public:
    int divide(int dividend, int divisor) {
        if (dividend == INT_MIN && divisor == -1) return INT_MAX;
        long m = labs(dividend), n = labs(divisor), res = 0;
        int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;
        if (n == 1) return sign == 1 ? m : -m;
        while (m >= n) {
            long t = n, p = 1;
            while (m >= (t << 1)) {
                t <<= 1;
                p <<= 1;
            }
            res += p;
            m -= t;
        }
        return sign == 1 ? res : -res;
    }
};

我們可以通過遞歸的方法來解使上面的解法變得更加簡潔:

解法二:

class Solution {
public:
    int divide(int dividend, int divisor) {
        long m = labs(dividend), n = labs(divisor), res = 0;
        if (m < n) return 0;
        long t = n, p = 1;
        while (m > (t << 1)) {
            t <<= 1;
            p <<= 1;
        }
        res += p + divide(m - t, n);
        if ((dividend < 0) ^ (divisor < 0)) res = -res;
        return res > INT_MAX ? INT_MAX : res;
    }
};

到此這篇關於C++實現LeetCode(29.兩數相除)的文章就介紹到這瞭,更多相關C++實現兩數相除內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: