LeetCode Divide Two Integers

Posted Learn++

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}
};

 

以上是关于LeetCode Divide Two Integers的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Divide Two Integers

[LeetCode]Divide Two Integers

Divide Two Integers -- LeetCode

LeetCode 29. Divide Two Integers

Leetcode 29. Divide Two Integers

[LeetCode] 29. Divide Two Integers