Effective perfect square
Given a positive integer num, write a function that returns True if num is a perfect square number, otherwise returns False.
Note: Do not use any built-in library functions, such as sqrt.
Example 1:
输入:16
输出:True
Example 2:
输入:14
输出:False
Solution 1: Incremental judgment
public:
bool isPerfectSquare(int num) {
int i=1;
long n=i*i;
while(n<=num)
{
if(n==num)
return true;
else
{
i++;
n=pow(i,2);
}
}
return false;
}
};
Solution 2: Dichotomy
class Solution {
public:
bool isPerfectSquare(int num) {
int start=1;
int end=num;
int mid=start+(end-start)/2;
while(start<=end)
{
if(pow(mid,2)>num)
{
end=mid-1;
}
else if(pow(mid,2)<num)
{
start=mid+1;
}
else return true;
mid=(end-start)/2+start;
}
return false;
}
};
Solution 3: Formula method
Use 1+3+5+7+9+…+(2n-1)=n^2, that is, the perfect square number must be the sum of the first n consecutive odd numbers
class Solution {
public:
bool isPerfectSquare(int num) {
int i=1;
while(num>0)
{
num-=i;
i+=2;
}
return num==0;
}
};