![](https://i-blog.csdnimg.cn/blog_migrate/bdf7e3d29aeebe0ac944b099013221ca.png)
方法一:使用内置的库函数
class Solution {
public boolean isPerfectSquare(int num) {
int x = (int) Math.sqrt(num);
return x * x == num;
}
}
方法二:暴力
class Solution {
public boolean isPerfectSquare(int num) {
long x = 1, square = 1;
while (square <= num) {
if (square == num) {
return true;
}
++x;
square = x * x;
}
return false;
}
}
方法三:二分查找
class Solution {
public boolean isPerfectSquare(int num) {
int left = 0, right = num;
while (left <= right) {
int mid = (right - left) / 2 + left;
long square = (long) mid * mid;
if (square < num) {
left = mid + 1;
} else if (square > num) {
right = mid - 1;
} else {
return true;
}
}
return false;
}
}