-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivide2Int.java
More file actions
85 lines (62 loc) · 1.94 KB
/
Divide2Int.java
File metadata and controls
85 lines (62 loc) · 1.94 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/* *****************************************************************************
* Name: Ada Lovelace
* Coursera User ID: 123456
* Last modified: October 16, 1842
**************************************************************************** */
public class Divide2Int {
/*public static int divide(long dividend, long divisor) {
int i = 0;
if (divisor > 0 && dividend > 0) {
while (dividend >= divisor) {
dividend -= divisor;
i++;
}
}
else if (divisor < 0 && dividend > 0) {
while (dividend >= -divisor) {
dividend += divisor;
i++;
}
i = -i;
}
else if (divisor < 0 && dividend < 0) {
while (-dividend >= -divisor) {
dividend -= divisor;
i++;
}
}
else if (divisor > 0 && dividend < 0) {
while (-dividend >= divisor) {
dividend += divisor;
i++;
}
i = -i;
}
return i;
}*/
public static int divide(int dividend, int divisor) {
if (divisor == 0) {
return dividend > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
if (dividend == 0) {
return 0;
}
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
boolean isNeg = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0);
long up = Math.abs((long) dividend);
long down = Math.abs((long) divisor);
int i = 0;
while (up >= down) {
up -= down;
i++;
}
return isNeg ? -i : i;
}
public static void main(String[] args) {
//Scanner scn = new Scanner(System.in);
int res = divide(Integer.MIN_VALUE, 2);
System.out.println(res);
}
}