LeetCode Divide Two Integers

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;
}
};

 

posted @ 2016-03-20 14:52  BestWangJie  阅读(277)  评论(0编辑  收藏  举报