367. Valid Perfect Square

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public boolean isPerfectSquare(int num) {
int left = 1, right = num;
int ans = 0;
while (left <= right) {
int mid = (left + right) >>> 1;
if (mid <= num / mid) {
ans = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}

return ans * ans == num;
}
}

Math

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public boolean isPerfectSquare(int num) {
int x = 1;
while (num > 0) {
num -= x;
x += 2;
}

return num == 0;
}
}

References

367. Valid Perfect Square