码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode[29]Divide Two Integers

时间:2015-02-10 14:46:30      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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

If it is overflow, return MAX_INT.

class Solution {
public:
    int divide(int dividend, int divisor) {
    if (dividend==0||divisor==0)return 0;
    int flag=1;
    if ((dividend<0&&divisor>0)||(dividend>0&&divisor<0))
        flag=0;
    if(dividend==divisor)return 1;
    long long a=dividend;
    long long b=divisor;
    a=abs(a);
    b=abs(b);
    if(a<b)return 0;
    long long b0=b;
    int res=0;
    int icount=0;
    int f=1;
    while (f)
    {
        while (a>=b)
        {
            b<<=1;
            icount++;
        }
        icount--;
        b>>=1;
        a-=b;
        res+=(1<<icount);
        if(a<b0)f=0;
        else
        {
            while(a<b)
            {
                b>>=1;
                icount--;
            }
        }
    }
    return flag?res:-res;
    }
};

 

leetcode[29]Divide Two Integers

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4283622.html

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