Not short, but maybe easy understand solution


  • 0
    N
    private long residual;
    private long result;
    
    public int divide(int dividend, int divisor) {
        //dividend/divisor
    	boolean belowZero = dividend>0^divisor>0;
        residual = dividend;
        long base = divisor;
    	residual = Math.abs(residual);
        base = Math.abs(base);
        if(!specialCase(base)){
            while(residual>=base){
    			divide(base);
    		}
        }
    	result = belowZero?0-result:result;
    	result = result>Integer.MAX_VALUE?Integer.MAX_VALUE:result;
    	return (int)result;
    }
    
    private boolean specialCase(long base){
        boolean res = true;
        if(base == 1){
    		result = residual;
    	}else if(base==residual){
    		result = 1;
    	}else if(base>residual){
    		result = 0;
    	}else{
    	    res = false;
    	}
    	return res;
    }
    
    private void divide(long divisor){
    	long localResult = 1;
    	long multiple = divisor;
    	while(multiple<=residual){
    		multiple = multiple<<1;
    		localResult = localResult<<1;
    	}
    	if(multiple > residual){
    		multiple = multiple>>1;
    		localResult = localResult>>1;
    	}
    	residual = residual - multiple;
    	result += localResult;
    }

Log in to reply
 

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