Divide two numbers,两数相除求商,不能用乘法,除法,取模运算
问题描述:求商,不能用乘法,除法,取模运算。
算法思路:不能用除法,那只能用减法,但是用减法,超时。可以用位移运算,每次除数左移,相当于2倍。
1 public class DividTwoIntegers { 2 public int divide(int dividend, int divisor) 3 { 4 if(divisor == 0) return Integer.MAX_VALUE; 5 if(divisor == -1 && dividend == Integer.MIN_VALUE) return Integer.MAX_VALUE; 6 7 long pDividend = Math.abs((long)dividend);//取绝对值,放溢出转化为long 8 long pDivisor = Math.abs((long)divisor); 9 10 int result = 0; 11 while(pDividend >= pDivisor) 12 { 13 int count = 0;//记录位移 14 while(pDividend >= (pDivisor << count)) 15 { 16 count ++; 17 } 18 result += (1 << (count-1)); 19 pDividend -= (pDivisor << (count-1)); 20 } 21 if((dividend <0 && divisor < 0) || (dividend > 0 && divisor > 0)) 22 { 23 return result; 24 } 25 else 26 { 27 return -result; 28 } 29 } 30 public static void main(String[] args) 31 { 32 DividTwoIntegers dt = new DividTwoIntegers(); 33 int a = dt.divide(10, 3); 34 System.out.println(a); 35 } 36 }