17-line code in Java (shorter than most high-voted Java ones :p)


  • -1
    M
    /*
        -- possible overflow: Integer.MIN_VALUE / (-1); anything / 0.
    */
    public class Solution {
        public int divide(int dividend, int divisor) {
            if (divisor == 0 || dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
            int sign = (dividend ^ divisor) >> 31;
            int quotient = divideHelper(Math.abs(Long.valueOf(dividend)), Math.abs(Long.valueOf(divisor)));
            return sign == 0 ? quotient : -quotient;
        }
        
        private int divideHelper(long top, long bot) {
            if (top < bot) return 0;
            long cur = bot;
            int count = 1;
            while (cur <= (top >>> 2)) {
                cur <<= 1;
                count <<= 1;
            }
            count += divideHelper(top - cur, bot);
            return count;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.