暴力
class Solution {
public:
bool isPerfectSquare(int num) {
for(long i = 1; i * i <= num; i++) {
if(i * i == num) return true;
}
return false;
}
};
二分查找
class Solution {
public:
bool isPerfectSquare(int num) {
int left = 1, right = num;
while(left <= right) {
int mid = left + (right - left) / 2;
long tmp = mid * mid;
if(tmp == num) return true;
else if(tmp < num) left = mid + 1;
else right = mid - 1;
}
return false;
}
};