-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDivideTwoIntegers.java
62 lines (49 loc) · 1.42 KB
/
DivideTwoIntegers.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package other;
/**
* @Author: Wenhang Chen
* @Description:给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。
* <p>
* 返回被除数 dividend 除以除数 divisor 得到的商。
* <p>
* 示例 1:
* <p>
* 输入: dividend = 10, divisor = 3
* 输出: 3
* 示例 2:
* <p>
* 输入: dividend = 7, divisor = -3
* 输出: -2
* @Date: Created in 13:57 12/24/2019
* @Modified by:
*/
public class DivideTwoIntegers {
public int divide(int dividend, int divisor) {
if (dividend == 0) return 0;
if (divisor == 1) return dividend;
if (divisor == -1) {
if (dividend == Integer.MIN_VALUE) return Integer.MAX_VALUE;
return -dividend;
}
long a = dividend;
long b = divisor;
int sign = 1;
if ((a > 0 && b < 0) || (a < 0 && b > 0)) {
sign = -1;
}
a = a > 0 ? a : -a;
b = b > 0 ? b : -b;
int res = div(a, b);
if (sign > 0) return res;
return -res;
}
int div(long a, long b) {
if (a < b) return 0;
long count = 1;
long tb = b; // 在后面的代码中不更新b
while ((tb + tb) <= a) {
count = count + count; // 最小解翻倍
tb = tb + tb; // 当前测试的值也翻倍
}
return (int) (count + div(a - tb, b));
}
}