-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivide2Sum.java
More file actions
54 lines (38 loc) · 1.21 KB
/
Divide2Sum.java
File metadata and controls
54 lines (38 loc) · 1.21 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
import java.util.*;
public class Divide2Sum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input
System.out.print("Enter dividend: ");
int dividend = sc.nextInt();
System.out.print("Enter divisor: ");
int divisor = sc.nextInt();
// Object create
Divide2Sum obj = new Divide2Sum();
// Function call
int result = obj.divide(dividend, divisor);
// Output
System.out.println("Result: " + result);
}
// Main divide function
public int divide(int dividend, int divisor) {
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
boolean negative = (dividend < 0) ^ (divisor < 0);
long dvd = Math.abs((long) dividend);
long dvs = Math.abs((long) divisor);
int result = 0;
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;
}
}