[leetcode]Divide Two Integers


* / mod 不能用

其實想想,乘法不就是加法嘛

a*b = b個a相加

 x / y = n 其實是 x = ny + r

我們來累加y,知道ny >=  x

就可以求的n了

但是這里又有個麻煩那的就是。。。累加的話,按我們的條件肯定是多算了一次啦

判斷ny == x 不等就減去一次就ok

不過這樣的結果就是TLE

INT_MAX和1,顯然要枚舉INT_MAX次

 

那腫么辦。。。

一次一次的枚舉確實有點2。。。

但就用增量吧,每次*2

這樣的想法是對的

但是。。問題是,累加。。。最后還是多算,覺得處理起來很麻煩啊

那換個似乎。。。我們用x每次減去y

直到x < y,那就是剛好

經常遇到這樣的問題,感覺很麻煩,換個角度就方便很多啊

 

class Solution {
public:
    int divide(int dividend, int divisor) {
        // without using * / mod
        // using add
        auto sign = [=](int x) {
            return x < 0 ? -1 : 1;
        };
        int d1 = sign(dividend);
        int d2 = sign(divisor);
        long long n1 = abs(static_cast<long long>(dividend));
        long long n2 = abs(static_cast<long long>(divisor));
        long long ans = 0;
        while(n1 >= n2) {
            long long base = n2;
            for(int i = 0 ; n1 >= base ; ++i) {
                n1 -= base;
                base <<= 1;
                ans +=  1LL << i;
            }
        }
        int res = static_cast<int>(ans);
        if(d1 != d2) return -res;
        else return res;
    }
};

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM