forked from Google-Developer-Student-Club-CCOEW/Competitive-Programming-2023-GDSC-CUMMINS-X-GDSC-MMCOE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdivide_twoint.java
31 lines (27 loc) Β· 1 KB
/
divide_twoint.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
public class divide_twoint {
public int divide(int dividend, int divisor) {
// Handle edge cases where the result may overflow.
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
// Determine the sign of the result.
int sign = (dividend > 0) ^ (divisor > 0) ? -1 : 1;
// Convert dividend and divisor to positive values for easier computation.
long ldividend = Math.abs((long) dividend);
long ldivisor = Math.abs((long) divisor);
// Initialize the result and perform subtraction.
long result = 0;
while (ldividend >= ldivisor) {
long temp = ldivisor;
long multiple = 1;
while (ldividend >= (temp << 1)) {
temp <<= 1;
multiple <<= 1;
}
ldividend -= temp;
result += multiple;
}
// Apply the sign to the result and return it.
return (int) (sign * result);
}
}