leetcode 29 兩數相除

這題挺好的!html

給定兩個整數,被除數 dividend 和除數 divisor。將兩數相除,要求不使用乘法、除法和 mod 運算符。

返回被除數 dividend 除以除數 divisor 獲得的商。

示例 1:

輸入: dividend = 10, divisor = 3
輸出: 3
示例 2:

輸入: dividend = 7, divisor = -3
輸出: -2
說明:

被除數和除數均爲 32 位有符號整數。
除數不爲 0。
假設咱們的環境只能存儲 32 位有符號整數,其數值範圍是 [231,  2311]。本題中,若是除法結果溢出,則返回 2311

題目

題目的主要難度在於不能使用除法,乘法,和取餘。
而後只能使用Int來儲存數字。
而後我先使用異或判斷是否同號,而後使用取絕對值而後直接二分,來搜索這個數字。
這裏的二分也不太同樣, 由於不能使用除號,因此我每次按照減法來解決,設定一個count,count成倍增長,而後被除數tempDivisor也成倍增長。這樣也實現了效率爲 O ( l o g n ) O(logn) java

class Solution {
    public int divide(int dividend, int divisor) {
        if (divisor==0)
            return -1;
        if (dividend==0)
            return 0;
        if (divisor == 1)
            return dividend;
        if (dividend==Integer.MIN_VALUE && divisor==-1)
            return Integer.MAX_VALUE;

        /** 符號位的處理參考了大佬的異或處理方法*/
        boolean negetive= (dividend ^ divisor)<0;
        // count計數如今除數是開始的幾倍
        int res=0, count=1;
        long tempDividend = Math.abs((long)dividend);
        long tempDivisor = Math.abs((long)divisor);
        
        while (tempDividend >= tempDivisor) {
            // 題目不讓使用乘除取模運算符
            tempDividend -= tempDivisor;
            res += count;

            if (tempDividend < Math.abs(divisor))
                break;
            
            if (tempDividend - tempDivisor < tempDivisor) {
                // System.out.println(count);
                // System.out.println(res);
                tempDivisor = Math.abs(divisor);
                count = 1;
                continue;
            }

            tempDivisor += tempDivisor;
            count += count;
        }
        return negetive ? 0-res: res;
    }
    public static void main(String[] args) {
        Solution s= new Solution();
        int ans = s.divide(37, 2);
        System.out.println(ans);
    }
}
相關文章
相關標籤/搜索