二分法:
class Solution {
public boolean isPerfectSquare(int num) {
int left = 0,right = num;
if(num==1)
{
return true;
}
while(left<right)
{
int mid = ((right-left)/2)+left;
long x = (long)mid*mid;
if(num<x)
{
right=mid;
}else if(num>x)
{
left=mid+1;
}else
{
return true;
}
}
return false;
}
}
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
暴力解法:
int n = 1;
while (num / n >= n) {
if (num % n==0 && num/n == n) {
return true;
}
n++;
}
return false;
1
2
3
4
5
6
7
8
牛顿迭代:
class Solution {
public boolean isPerfectSquare(int num) {
double x = num;
while(x * x - num > 0.00000001){
x = (num/x + x)/2;
}
int y = (int)x;
return y*y == num;
}
}