A concise Java solution


  • 4
    H
        public int divide(int dividend, int divisor) {
            if (dividend == Integer.MIN_VALUE && divisor == -1)
                return Integer.MAX_VALUE;
    
            long divd = Math.abs((long)dividend);
            long divs = Math.abs((long)divisor);
    
            int ret = 0;
            while (divd >= divs) {
                int counter = 0;
                while (divd >= (divs << counter)) { // keep multiply by 2 until divs > divd
                    counter++;
                }
                counter--;  // rollback counter so that (divs<<counter) <= divd
                ret += 1 << counter;  // quotient
                divd -= divs << counter;
            }
    
            if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0))
                return ret;
            else
                return -ret;
        }

  • 1
    D

    you do not have to deal with the corner case that
    dividend = integer.MIN_VALUE; divisor = -1
    you can do
    result += ((long)1 << counter);
    rather than
    result += (1 << counter);
    the reason is that, you cannot shift int left 32 times, as Integer.MAX_VALUE = 2^31 -1


Log in to reply
 

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