题目:
Divide two integers without using multiplication, division and mod operator.
题解:
这道题我自己没想出来。。。乘除取模都不让用。。那只有加减了。。。我参考的http://blog.csdn.net/perfect8886/article/details/23040143
代码如下:
1 public int divide(int dividend, int divisor) {
2 if (dividend == 0 || divisor == 0) {
3 return 0;
4 }
5 boolean isNeg = (dividend > 0 && divisor < 0)
6 || (dividend < 0 && divisor > 0);
7 long a = Math.abs((long) dividend);
8 long b = Math.abs((long) divisor);
9 if (b > a) {
10 return 0;
11 }
12
13 long sum = 0;
14 long pow = 0;
15 int result = 0;
16 while (a >= b) {
17 pow = 1;
18 sum = b;
19 while (sum + sum <= a) {
20 sum += sum;
21 pow += pow;
22 }
23 a -= sum;
24 result += pow;
25 }
26 return isNeg ? -result : result;
27 }
2 if (dividend == 0 || divisor == 0) {
3 return 0;
4 }
5 boolean isNeg = (dividend > 0 && divisor < 0)
6 || (dividend < 0 && divisor > 0);
7 long a = Math.abs((long) dividend);
8 long b = Math.abs((long) divisor);
9 if (b > a) {
10 return 0;
11 }
12
13 long sum = 0;
14 long pow = 0;
15 int result = 0;
16 while (a >= b) {
17 pow = 1;
18 sum = b;
19 while (sum + sum <= a) {
20 sum += sum;
21 pow += pow;
22 }
23 a -= sum;
24 result += pow;
25 }
26 return isNeg ? -result : result;
27 }
Reference:
http://blog.csdn.net/perfect8886/article/details/23040143