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

LeetCode Divide Two Integers

时间:2016-03-20 15:58:49      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

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

If it is overflow, return MAX_INT.

举个例子比较容易理解,74 / 5, 这里 5*2=10 < 10*2=20 < 20*2=40 <  40*2=80,可以得到 5*8<74;然后剩下34,使用这一方法继续计算5*4=20 < 34,剩余14, 5*2<14,余下4舍去。故结果为8+4+2=14。

class Solution {
public:
    int divide(int dividend, int divisor) 
{
	int ret = 0;
	int count = 0;
	
	long long fDivisor = divisor;
	long long fDividend = dividend;
	long long a = abs(fDividend);
	long long b = abs(fDivisor);
	long long sum = 0;
	int final = 0;
	bool flag = false;
	if(!fDivisor || (fDividend==INT_MIN&&fDivisor==(-1))) return INT_MAX;
	if(fDivisor ==0 || fDividend ==0)
		return 0;

	if(a  < b)
	{
		return 0;
	}

	while(a >= b)
	{
		int count = 1;
		sum = b;
		while(sum + sum < a)
		{
			sum += sum;
			count += count;
		}
		a -= sum;
		final += count;
	}

	if(fDividend * fDivisor < 0)
	{
	 final = (-1)*final;
	}
	return final;
}
};

 

LeetCode Divide Two Integers

标签:

原文地址:http://www.cnblogs.com/bestwangjie/p/5297789.html

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