public int divide(int dividend, int divisor) {
long result = divideLong(dividend, divisor);
return result > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)result;
}
// It's easy to handle edge cases when
// operate with long numbers rather than int
public long divideLong(long dividend, long divisor) {
// Remember the sign
boolean negative = dividend < 0 != divisor < 0;
// Make dividend and divisor unsign
if (dividend < 0) dividend = dividend;
if (divisor < 0) divisor = divisor;
// Return if nothing to divide
if (dividend < divisor) return 0;
// Sum divisor 2, 4, 8, 16, 32 .... times
long sum = divisor;
long divide = 1;
while ((sum+sum) <= dividend) {
sum += sum;
divide += divide;
}
// Make a recursive call for (devidedsum) and add it to the result
return negative ? (divide + divideLong((dividendsum), divisor)) :
(divide + divideLong((dividendsum), divisor));
}
Accepted Java solution with comments.


You can add an exception handler if you like, but here in this case if you do nothing about the 0 divisor, the exception will be thrown to the calling method, maybe the main function in the test code which we cannot see. In fact, such exception is a kind of runtime exception which you can either throw or just leave it alone.

Nice solution, it's really easy to understand!
I modified your codes a little bit though, to avoid checking whether it is negative in the recursive calls.public int divide(int dividend, int divisor) { if (dividend == 0  divisor == 0) return 0; long d1 = dividend, d2 = divisor; long result = divideLong(Math.abs(d1), Math.abs(d2)); result = d1 * d2 < 0 ? result : result; if (result > Integer.MAX_VALUE  result < Integer.MIN_VALUE) return Integer.MAX_VALUE; return (int) result; } private long divideLong(long dividend, long divisor) { if (dividend < divisor) return 0; long sum = divisor, divideTimes = 1; while (sum + sum <= dividend) { sum += sum; divideTimes += divideTimes; } return divideTimes + divideLong(dividend  sum, divisor); }
