-
Notifications
You must be signed in to change notification settings - Fork 43
/
ValidPerfectSquare.java
60 lines (50 loc) · 1.38 KB
/
ValidPerfectSquare.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
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
package LeetCodeJava.BinarySearch;
// https://leetcode.com/problems/valid-perfect-square/
public class ValidPerfectSquare {
// V0
// IDEA : BINARY SEARCH
public boolean isPerfectSquare(int num) {
if (num < 2) {
return true;
}
long left = 2;
long right = num / 2; // NOTE !!!, "long right = num;" is OK as well
long x;
long guessSquared;
while (left <= right) {
x = (left + right) / 2;
guessSquared = x * x;
if (guessSquared == num) {
return true;
}
if (guessSquared > num) {
right = x - 1;
} else {
left = x + 1;
}
}
return false;
}
// V1
// IDEA : BINARY SEARCH
// https://leetcode.com/problems/valid-perfect-square/editorial/
public boolean isPerfectSquare_1(int num) {
if (num < 2) {
return true;
}
long left = 2, right = num / 2, x, guessSquared;
while (left <= right) {
x = left + (right - left) / 2;
guessSquared = x * x;
if (guessSquared == num) {
return true;
}
if (guessSquared > num) {
right = x - 1;
} else {
left = x + 1;
}
}
return false;
}
}