方法一:迭代法
class Solution {
public:
bool isPerfectSquare(int num) {
if(num==1 || num==0)
return true;
long i=1;
while(i*i<num)
i++;
return i*i==num;
}
};
方法二:二分法
class Solution {
public:
bool isPerfectSquare(int num) {
if(num==1 || num==0)
return true;
long left=2,right=num/2;
while(left<=right){
long mid=left+(right-left)/2;
if(mid*mid==num)
return true;
if(mid*mid>num){
right=mid-1;
}
else{
left=mid+1;
}
}
return false;
}
};