首页 > 代码库 > HappyLeetcode45:Divide Two Integers

HappyLeetcode45:Divide Two Integers

Divide Two Integers
Total Accepted: 26724 Total Submissions: 167045My 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