1. 程式人生 > >【LeetCode】29. Divide Two Integers - Java實現

【LeetCode】29. Divide Two Integers - Java實現

文章目錄

1. 題目描述:

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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 2^31 − 1 when the division result overflows.

2. 思路分析:

題目的意思是在不使用乘法,除法和取模操作的情況下實現整數的除法運算,整型溢位則返回最大整型。

既然不能用乘、除、取模,只能用移位操作來完成了。將除數 divisor 每次左移一位,找到最接近被除數且不大於被除數 dividend的一個數,然後將被除數減去這個數,繼續之前的操作。例如:31除以3,將3不斷左移,直到左移3位後達到最接近31且不大於31的數,即3*2*2*2=24(此時相當於將3乘以了8,這個8是結果的一部分),然後將31-24=7,繼續之前的操作,左移3,直到最接近7且不大於7的一個數,即將3左移一位得到3*2=6(這個2也是結果的一部分),然後7-6=1,繼續之前的操作,因為3已經大於1了,所以不需要左移了,即得到最後的結果為:8+2=10

3. Java程式碼:

原始碼見我GiHub主頁

程式碼:

public static int divide(int dividend, int divisor) {
    if (divisor == 0) {
        return Integer.MAX_VALUE;
    }

    // 用long型來儲存,防止越界
    long dividendLong = dividend;
    long divisorLong = divisor;

    long dividendAbs = Math.abs(dividendLong);
    long divisorAbs = Math.abs(divisorLong);
    if (dividendAbs < divisorAbs) {
        return 0;
    }

    long tempResult = 1;
    long m = dividendAbs;
    long n = divisorAbs;
    // 通過移位找到最大的乘數,使得和 n 的乘積小於等於 m
    while ((m >> 1) >= n) {
        tempResult = tempResult << 1;
        n = n << 1;
    }

    // 遞迴求解
    long result = tempResult + divide((int)(m - n), (int)divisorAbs);

    // 確定最後結果的符號,及是否越界
    if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) {
        return -result < Integer.MIN_VALUE ? Integer.MIN_VALUE : (int)-result;
    } else {
        return result > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)result;
    }
}