首页 > 代码库 > Divide Two Integers

Divide Two Integers

题目

Divide two integers without using multiplication, division and mod operator.

方法

将除数倍加,直到大于被除数。
	    public int divide(int dividend, int divisor) {
	        int flag = 0;
	        if((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)){
	            flag = 1;
	        }
	        
	        long divid = Math.abs((long)dividend);
	        long divis = Math.abs((long)divisor);
	        
	        long n;
	        
	        int quotient = 0;
	        
	        int quo = 0;
	        while(divid >= divis){
	            n = divis;
	            quo = 1;
	            while(n + n <= divid){
	                n = n + n;
	                quo = quo + quo;
	            }
	            divid =divid - n;
	            quotient += quo;
	        }
	        
	        if(flag == 1){
	            return -quotient;
	        }
	        return quotient;
	    }