LeetCode 29. Divide Two Integers
divide two integers without using * / and %.
the range of integer is: [-2^31, 2^31 - 1]
return integer.
class Solution {
public int divide(int dividend, int divisor) {
int sign = 1;
if (dividend > 0 ^ divisor > 0) sign = -1;
long ldividend = Math.abs((long) dividend);
long ldivisor = Math.abs((long) divisor);
if (dividend == 0) return 0;
long lres = divide(ldividend, ldivisor);
//do the final process to the final results
int res = 0;
if (lres > Integer.MAX_VALUE) {
res = sign == 1? Integer.MAX_VALUE: Integer.MIN_VALUE;
} else {
res = (int) (sign * lres);
}
return res;
}
private long divide(long ldividend, long ldivisor) {
if (ldividend < ldivisor) return 0;
//core function
long sum = ldivisor;
long cumulative = 1;
while (sum * 2 < ldividend) {
sum = sum * 2;
cumulative = cumulative * 2;
}
return cumulative + divide(ldividend - sum, ldivisor);
}
}

浙公网安备 33010602011771号