您的位置:首页 > 其它

LeetCode-29.Divide Two Integers

2016-06-04 21:39 411 查看
Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

public int Divide(int dividend, int divisor)
{
if (divisor == 0 || (dividend == int.MinValue && divisor == -1))
return int.MaxValue;
int res = 0;
bool isNeg = (dividend < 0) ^ (divisor < 0);
long dvd = Math.Abs((long)dividend);
long dvs = Math.Abs((long)divisor);
while (dvs <= dvd)
{
long temp = dvs, mul = 1;
while (dvd >= temp << 1)
{
temp <<= 1;
mul <<= 1;
}
dvd -= temp;
res += (int)mul;
}
return isNeg ? -res : res;
}

参考 

https://leetcode.com/discuss/38997/detailed-explained-8ms-c-solution

http://blog.csdn.net/linhuanmars/article/details/20024907
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode