I am using the idea of @jianchao.li.fighter to implement the Java version. Could someone explain to me why my code does not work for 2147483647 / 2? It seems to me that overflow at the line sub = dvs << ++shift; is the cause but I am not sure. How can I correct my code to make it work?

public int divide(int dividend, int divisor) { if (divisor == 0 || dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } boolean isNegative = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0); long dvd = Math.abs((long)dividend); long dvs = Math.abs((long)divisor); if (dvd < dvs) return 0; if (divisor == 1) return dividend; int shift = 0; long sub = dvs; while (dvd >= sub) { sub = dvs << ++shift; } int quotient = 1 << --shift; if (dvd - (sub >> 1) >= dvs) { quotient++; } return isNegative ? -quotient : quotient; }Divide Two Integers