-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivideTwoIntegers.java
More file actions
43 lines (31 loc) · 1004 Bytes
/
DivideTwoIntegers.java
File metadata and controls
43 lines (31 loc) · 1004 Bytes
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
public class DivideTwoIntegers {
public static int divide(int dividend, int divisor) {
// Edge case (overflow)
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
// Sign check
boolean negative = (dividend < 0) ^ (divisor < 0);
long dvd = Math.abs((long) dividend);
long dvs = Math.abs((long) divisor);
int result = 0;
// Bit manipulation logic
while (dvd >= dvs) {
long temp = dvs;
int multiple = 1;
while (dvd >= (temp << 1)) {
temp <<= 1;
multiple <<= 1;
}
dvd -= temp;
result += multiple;
}
return negative ? -result : result;
}
public static void main(String[] args) {
int dividend = 15;
int divisor = 3;
int result = divide(dividend, divisor);
System.out.println("Result: " + result);
}
}