# Divide two numbers，两数相除求商，不能用乘法，除法，取模运算

 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 }

posted @ 2016-06-04 16:54  32ddd  阅读(477)  评论(0编辑  收藏