29. Divide Two Integers

1.问题描述

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

If it is overflow, return MAX_INT.

2.解题思路

采用二分法,每次让除数以2倍的形式递增,只要递增结果小于被除数,则继续递增,如果递增时超过了,则记住递增前的数,然后用被除数减去递增前的数,再次倍数递增,直到被除数的值小于除数

3.代码实现

class Solution {
public:
long long myAbs(const int x) {
	if (x > 0)
		return x;
	return -(static_cast(x));
}
int divide(int dividend, int divisor) {

	if (divisor == 0||dividend == 0)
		return 0;
	long long count = 0;
	long long tmp = 0;
	long long absDividend = myAbs(dividend);
	long long absDivisor = myAbs(divisor);
	long long sum = absDivisor;
	while (absDividend >= absDivisor) {
		tmp = 1;
		sum = absDivisor;
		while (sum + sum <= absDividend) {
			sum += sum;
			tmp += tmp;
		}
		count += tmp;
		absDividend -= sum;
	}
	if (divisor < 0 && dividend>0 || divisor > 0 && dividend < 0)
		count =  -count;
	if (count > 2147483647)
		return 2147483647;
	return count;
}
};

4.结果截图

29. Divide Two Integers_第1张图片

你可能感兴趣的:(LeetCode)