Closest Divisors LeetCode solution in Java

1
class Solution {
2
public int[] closestDivisors(int num) {
3
int ans[] = new int[2];
4
double a = Math.sqrt(num + 1);
5
double b = Math.sqrt(num + 2);
6

7
if (num == 1) {
8
ans[0] = 1;
9
ans[1] = 2;
10
return ans;
11
} else if (a % 1 == 0) {
12
ans[0] = (int) a;
13
ans[1] = (int) b;
14
return ans;
15
} else if (b % 1 == 0) {
16
ans[0] = (int) b;
17
ans[1] = (int) b;
18
return ans;
19
} else {
20
int m = (int) Math.sqrt(num);
21
int diff1 = Integer.MAX_VALUE;
22
int y = 0, z = 0, w = 0, f = 0;
23

24
for (int i = 2; i <= m; i++) {
25
if ((num + 1) % i == 0) {
26
y = i;
27
z = (num + 1) / y;
28
int r = Math.abs(y - z);
29

30
if (r < diff1) {
31
diff1 = r;
32
}
33
}
34
}
35

36
int diff2 = Integer.MAX_VALUE;
37

38
for (int i = 2; i <= m; i++) {
39
if ((num + 2) % i == 0) {
40
w = i;
41
f = (num + 2) / w;
42
int r = Math.abs(w - f);
43

44
if (r < diff2) {
45
diff2 = r;
46
}
47
}
48
}
49

50
if (diff1 < diff2) {
51
ans[0] = y;
52
ans[1] = z;
53
return ans;
54
} else {
55
ans[0] = w;
56
ans[1] = f;
57
return ans;
58
}
59
}
60
}
61
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0