Java solution without long


  • 0
    M
    private int divide_res = 0;
    public int divide(int dividend, int divisor) {
    	boolean neg = false;
    	if(dividend == Integer.MIN_VALUE){
    		if(divisor == -1) return Integer.MAX_VALUE;
    		else if(divisor == 1) return Integer.MIN_VALUE;
    		else if(divisor > 1){
    			dividend += divisor;
    			divide_res ++;
    		}else if(divisor == Integer.MIN_VALUE){
    			return 1;
    		}else{
    			dividend -= divisor;
    			divide_res ++;
    		}
    	}
    	if(divisor == Integer.MIN_VALUE){
    		return 0;
    	}
    	if((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)){
    		neg = true;
    	}
    	divideHelper(Math.abs(dividend), Math.abs(divisor));
    	return !neg ? divide_res : 0 - divide_res;
    }
    
    public void divideHelper(int dividend, int divisor){
    	if(dividend < divisor)
    		return ;
    	int count = 1, d = divisor;
    	while(divisor <= dividend && divisor > 0){
    		divide_res += count;
    		dividend -= divisor;
    		divisor <<= 1;
    		count <<= 1;
    	}
    	divideHelper(dividend, d);
    }

Log in to reply
 

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