Java recursive solution short&clear


  • 1
    public int divide(int dividend, int divisor) {
        int sign = ((dividend ^ divisor)>>>31) == 1? -1:1;
        //divide zero
        if(divisor == 0) return dividend > 0? Integer.MAX_VALUE:Integer.MIN_VALUE;
        //overflow
        if(divisor == -1 && dividend == Integer.MIN_VALUE) return Integer.MAX_VALUE;
        //deal with Integer.MIN_VALUE cases
        long divisorl = Math.abs((long) divisor);
        long dividendl = Math.abs((long)dividend);
        long lans = dividel(dividendl,divisorl);
        return  (int) (sign * lans);
    }
    
    public long dividel(long dividendl, long divisorl){
        if(dividendl < divisorl)
            return 0;
        int i = 0;
        while(dividendl > (divisorl << (i+1) )) i += 1;
        return (long)(1<<i)+dividel(dividendl-(divisorl<<i),divisorl);
    }

Log in to reply
 

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