Java 40ms Solution Without Using long


  • 0
    public int divide(int dividend, int divisor) {
        // cases of overflow
        if(divisor == 0) return Integer.MAX_VALUE;
        if( dividend == Integer.MIN_VALUE  && divisor == -1 ) return Integer.MAX_VALUE;
    
        // determin wheter the result is negative 
        boolean negative = false;
        if(  dividend > 0 && divisor < 0) negative = true;
        if(  dividend < 0 && divisor > 0) negative = true;
        
        // convert positive to negative 
        int x = dividend;
        int y = divisor;
        if(  dividend > 0) x = - dividend;
        if(  divisor > 0) y = - divisor;
        
        int tmp = helper(x, y);
        if( negative ) tmp = - tmp;
        return tmp;   
    }
    
    // this function only calculate division between negative numbers 
    int helper(int dividend, int divisor){            
        ArrayList<Integer> ls = new ArrayList<Integer>();
        int x = divisor;
        ls.add(x);
        while(dividend - x <= x){ // dividend <= 2*x
            x = x << 1;
            ls.add(x);
        }
        
        int res = 0;
        for(int i = ls.size() - 1; i >= 0 ; i--){
            if(i < ls.size() - 1) res = res << 1;
            if(dividend <= ls.get(i)) {
                res++;
                dividend -= ls.get(i);
            }
        }
        return res;
    }

Log in to reply
 

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