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

#29 Divide Two Integers

时间:2015-07-20 09:19:59      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c   math   

题目链接:https://leetcode.com/problems/divide-two-integers/


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

If it is overflow, return MAX_INT.



int divide(int dividend, int divisor) {
    if (dividend == INT_MIN && divisor == -1)   //被除数为-2147483648除数为-1时,商溢出
		return INT_MAX;
	int quotient = 0;
	int flag = (dividend>0&&divisor>0 || dividend<0&&divisor<0) ? 1 : -1;
	unsigned int a = dividend > 0 ? dividend : -dividend;   //无符号整数防止-2147483648取绝对值后溢出
	unsigned int b = divisor > 0 ? divisor : -divisor;
    unsigned int tmp = a;
    int digit = 0;          //商的二进制位数
    while(tmp >= b) {  //计算商的二进制位数
        ++digit;
        tmp >>= 1;
    }
    while(digit--) {    //类似除法的笔算过程,从最高位开始除算出商的各个位数上的数值
        unsigned int divi = b << digit;        //在除数后面补0使得除被除数得到个位数
        quotient = (quotient << 1) + (a >= divi ? 1 : 0);       //高位的商移位后要加权(左移加权2)
        a = a >= divi ? a - divi : a;
    }
    if(flag < 0)
        quotient = -quotient;
    return quotient;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

#29 Divide Two Integers

标签:leetcode   c   math   

原文地址:http://blog.csdn.net/ice_camel/article/details/46959549

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