Clean/easy 2ms java solution


  • 0
    L
    public int divide(int dividend, int divisor) {
        if (divisor == 0) return Integer.MAX_VALUE;
        if (dividend == 0) return 0;
        if (divisor == -1 && dividend == Integer.MIN_VALUE) return Integer.MAX_VALUE;
        
        int flag = 1;
        if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) flag = -1;
    
        int res = 0;
        long dvd = Math.abs((long) dividend);
        long div = Math.abs((long) divisor);
        
        while (dvd >= div) {
            long x = 1;
            long ndiv = div;
            while ((ndiv<<1) < dvd) {
                x <<= 1;
                ndiv <<= 1;
            }
            
            res += x;
            dvd = dvd - ndiv;
        }
    
        return res * flag;
    }

  • 0
    A

    Do you know you cannot use multiply operator


  • 0
    B

    He can replace that line with a check if res < 0 then return 0 - res else return res.


Log in to reply
 

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