brute force从1算到n^2(>num)
找到前后区间
class Solution {
public:
bool isPerfectSquare(int num) {
if(num==1) return true;
long cur=num;
while((cur/2)*(cur/2)>num){
cur = cur/2;
}
int h=cur;
for(int i=cur/2;i<cur;i++){
if(i*i==num) return true;
}
return false;
}
};
边遍历边缩小区间
class Solution {
public:
bool isPerfectSquare(int num) {
for (int i = 1; i <= num / i; ++i) {
if (i * i == num) return true;
}
return false;
}
};
class Solution {
public:
bool isPerfectSquare(int num) {
if(num==1) return true;
long l=0, r=num/2+1;
while(l<r){
long mid = l+(r-l)/2;
long cur = mid*mid;
if(cur==num) return true;
else if(num>cur) l=1+mid;
else r=mid;
}
return false;
}
};
1 = 1
4 = 1 + 3
9 = 1 + 3 + 5
16 = 1 + 3 + 5 + 7
25 = 1 + 3 + 5 + 7 + 9
36 = 1 + 3 + 5 + 7 + 9 + 11
....
1+3+...+(2n-1) = (2n-1 + 1)n/2 = n*n
class Solution {
public:
bool isPerfectSquare(int num) {
int i = 1;
while (num > 0) {
num -= i;
i += 2;
}
return num == 0;
}
};
class Solution {
public:
bool isPerfectSquare(int num) {
long x = num;
while (x * x > num) {
x = (x + num / x) / 2;
}
return x * x == num;
}
};
Reference: