二分查找,用了magic num防止溢出 这题也可以牛顿切线或者O(1)的那个奇怪游戏中的算法 https://www.wikiwand.com/en/Fast_inverse_square_root
class Solution {
public:
bool isPerfectSquare(int num) {
int left = 1, right = min(num>>1, 46340); //sqrt(2147483647), avoid overflow
while(left<right){
int mid = (left+right) >> 1;
if(mid*mid > num) right = mid-1;
else if(mid*mid < num) left = mid+1;
else return true;
}
return left*left == num;
}
};