HappyLeetcode45:Divide Two Integers

來源:互聯網
上載者:User

標籤:

Divide Two Integers Total Accepted: 26724 Total Submissions: 167045 My Submissions

Question Solution

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

這道題要不是參考別人的答案,恐怕較難得到思路。總體而言就是二分法。二分尋找是很熟悉的內容了,但是真的將相關方法到應用的時候還是覺得略有困難。

參考文獻:http://www.cnblogs.com/panda_lin/p/divide_two_integers.html

這道題算是一種很不錯的經驗吧。把代碼奉上:

class Solution {public:    unsigned long long newdivide(unsigned long long dividend, unsigned long long divisor)    {        unsigned long long temp=divisor,left;        unsigned long long result=1;        if (dividend < divisor)            return 0;        while (temp <= dividend)        {                        left = dividend - temp;            temp <<= 1;            if (temp > dividend)                break;            else                result <<= 1;        }        return result + newdivide(left, divisor);    }    int divide(int dividend, int divisor) {        if (divisor == 0)            throw 1;//拋出一個錯誤出去        bool positive = (dividend >= 0 && divisor > 0) || (dividend <= 0 && divisor < 0);        unsigned long long _dividend = abs((long long)dividend);        unsigned long long _divisor = abs((long long)divisor);        long long tempresult=positive ? newdivide(_dividend, _divisor) : -1 * newdivide(_dividend, _divisor);        if (abs(tempresult) >= INT_MAX)            tempresult = positive ? INT_MAX : INT_MIN;        return  tempresult;    }};

再學習一下二分法的內容:

HappyLeetcode45:Divide Two Integers

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.