Topic
Divide-integers without using multiplication, division and mod operator.
If It is overflow, return max_int.
The title means: Do not use the *,/,% operator for division operations
Ideas
The most direct idea of the problem is that the divisor is subtracted every time, the calculation is reduced by how many times, that is, the request. But the efficiency of this approach is too low, imagine dividend is Integer.max_value (2147483647), the divisor is 1, then 2,147,483,647 times, it will obviously happen tle.
A better approach:
Instead of subtracting the divisor each time, the divisor is incremented each time, resulting in a corresponding multiple of the divisor.
Code
public class P029_DivideTwoIntegers {
public int divide(int dividend, int divisor) {
int sign = 1;
if (dividend < 0) {
sign = -sign;
}
if (divisor < 0) {
sign = -sign;
}
long n1 = Math.abs((long)dividend);
long n2 = Math.abs((long)divisor);
long ans = 0;//用long是为了处理溢出,比如当ans为2147483648的情况
while (n1 >= n2) {
long base = n2;
for (int i = 0; n1 >= base; i++) {
n1 -= base;
base<<=1;
ans+=1<<i;
}
}
//处理溢出的情况
//int的范围为-2147483648到2147483647
//dividend=Integer.MIN_VALUE,即-2147483648
//divisor=-1,此时将发生溢出,按题目要求,返回Integer.MAX_VALUE
if (ans * sign > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
return (int) (sign*ans);
}
}
From for notes (Wiz)
"Leetcode" P029_dividetwointegers