forked from szl0072/Leetcode-Solution-Code
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDivideTwoIntegers.java
52 lines (46 loc) · 1.37 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
52
package leetcode;
/**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : DivideTwoIntegers
* Creator : Edward
* Date : Nov, 2017
* Description : 29. Divide Two Integers
*/
public class DivideTwoIntegers {
/**
* Divide two integers without using multiplication, division and mod operator.
* 1, + -
* 2, 越界
* 3, = 0 3/5
* 4, 正常
time : O(logn)
space : O(logn)
* @param dividend
* @param divisor
* @return
*/
public int divide(int dividend, int divisor) {
int sign = 1;
if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) sign = -1;
long ldividend = Math.abs((long)dividend);
long ldivisor = Math.abs((long)divisor);
if (ldividend < ldivisor || ldividend == 0) return 0;
long lres = divide(ldividend, ldivisor);
int res = 0;
if (lres > Integer.MAX_VALUE) {
res = (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
} else res = (int)(sign * lres);
return res;
}
public long divide(long ldividend, long ldivisor) {
if (ldividend < ldivisor) return 0;
long sum = ldivisor;
long multiple = 1;
while ((sum + sum) <= ldividend) {
sum += sum;
multiple += multiple;
}
return multiple + divide(ldividend - sum, ldivisor);
}
}