题解:
题解:
思路1:二分法寻找平方数
思路2:等差数列求和公式判断是否为平方数
代码如下:
// 思路1 二分法求平方数
using LL = long long;
class Solution {
public:
// 思路:二分法
bool isPerfectSquare(int n) {
LL l=1,r=n/2;
while(l<r)
{
LL mid=l+r>>1;
if(mid*mid>=n)r=mid;
else l=mid+1;
}
return l*l==n;
}
};
// 思路2 等差数列
class Solution {
public:
// 等差数列求和公式:1+3+5+...+(2*n-1)=(2*n-1+1)/2*n=n*n
bool isPerfectSquare(int n) {
int x=1;
while(n>0)n-=x,x+=2;
return n==0;
}
};