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

[leetcode] 29 Divide Two Integers

时间:2015-01-26 13:45:55      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

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

If it is overflow, return MAX_INT.

基本的用减法操作可以实现除法,但是速度较慢。为了加快速度,每次将除数和结果加倍。

代码:

    int divide(int dividend, int divisor) {  //C++
        if(dividend == 0)
            return 0;
        if(divisor ==0 || dividend == -2147483648&&divisor ==-1)
            return 2147483647;
        
        bool sameFlag = true;
        if((dividend >0 && divisor <0 )||(dividend <0 && divisor >0))
            sameFlag = false;
        
        long tmpdividend = (dividend >0)? dividend : -(long)(dividend);
        long tmpdivisor  = (divisor >0) ? divisor  : -(long)(divisor);
        int result = 0;
        
        while(tmpdividend >=tmpdivisor){
            int size = 1;
            long t = tmpdivisor;    
            while(tmpdividend >= t)
            {
                result +=size;
                tmpdividend -= t;
                t = t+t;
                size = size+size;
            }
        }
        
        if(!sameFlag)
            result = -result;
        return result;
    }


[leetcode] 29 Divide Two Integers

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/43150571

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