HappyLeetcode45:Divide Two Integers

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;

    }

};

再学习一下二分法的内容:

对于区间[a,b]上连续不断且f(a)·f(b)<0的函数y=f(x),通过不断地把函数f(x)的零点所在的区间一分为二,使区间的两个端点逐步逼近零点,进而得到零点近似值的方法叫二分法。

你可能感兴趣的:(LeetCode)