码迷,mamicode.com
首页 > 移动开发 > 详细

HappyLeetcode45:Divide Two Integers

时间:2015-01-19 14:03:27      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/chengxuyuanxiaowang/p/4233458.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!