题目原型:
Divide two integers without using multiplication, division and mod operator.
思路一:
采用最普通的方式,累减法。
注意:为防止溢出,我们另外设置两个变量存储被除数和除数。
public int divide(int dividend, int divisor) { //处理符号 if(dividend==0) return 0; int sign = 1; if(dividend<0) sign = sign * (-1); if(divisor<0) sign = sign * (-1); long dividendtemp = Math.abs(dividend); long divisortemp = Math.abs(divisor); if(divisortemp==1) return (int)(sign*dividendtemp); int result = 0; long sum = divisortemp; if(dividendtemp>=divisortemp) { while(sum<dividendtemp) { result++; sum+=divisortemp; } } return sign*result; }
思路二:
基于思路一过于“笨”,当处理被除数很大而除数很小时反应很慢,下面改进一下,即采用移位运算:
public int divide(int dividend, int divisor) { //处理符号 if(dividend==0) return 0; int sign = 1; if(dividend<0) sign = sign * (-1); if(divisor<0) sign = sign * (-1); //防止溢出 long dividendtemp = Math.abs((long)dividend); long divisortemp = Math.abs((long)divisor); if(divisortemp==1) return (int)(sign*dividendtemp); int result = 0; int threshold = 0; while((divisortemp<<threshold)<=dividendtemp) { threshold++; } threshold--; for(int i = threshold;i>=0;i--) { if((divisortemp<<i)<=dividendtemp) { result+=(1<<i); dividendtemp-=(divisortemp<<i); } } return sign*result; }