LeetCode 28. Divide Two Integers

参考了XOR的题解


模拟补码除法,a为被除数绝对值,b为除数绝对值。

每次除数增加一倍,当被除数<2*除数时,被除数减去当前的除数,增加商,并重新开始迭代:

    	while (a >= b)
    	{
    		long long sum = b;
    		int cnt = 1;
    		while (sum + sum <= a)
    		{
    			sum += sum; // 左移
    			cnt += cnt; // 左移
    		}
    		a -= sum;
    		quotient += cnt;
    	}


取绝对值时有个trick, 见完整代码:

class Solution 
{
public:
	int divide(int dividend, int divisor) 
	{
		bool negative = (dividend<0&&divisor>0) || (dividend>0&&divisor<0);
		// 先转型为long long, 否则abs(-2147483648)会溢出,因为int的上界为2147483647
		long long c = dividend, d = divisor; // 在LeetCode上 long long a = abs(long long(dividend)) 编译错误
		long long a = abs(c), b = abs(d);
		int quotient = 0;


		while (a >= b)
		{
			long long sum = b;
			int cnt = 1;
			while (sum + sum <= a)
			{
				sum += sum;
				cnt += cnt;
			}
			a -= sum;
			quotient += cnt;
		}


		return negative? -quotient: quotient;
	}
};


你可能感兴趣的:(LeetCode,divide)