LeetCode 367. 有效的完全平方数
思路:
核心为最后一步判断当二分结束后值为及接近一个整数的浮点数(如2.9xxxx)此时加上极小数(1e-6)取整再平方,若与num相等则为完全平方数
class Solution {
public:
bool isPerfectSquare(int num) {
if (num == 0) return true;
if (num == 1) return true;
double l = 0, r = num;
while (r - l > 1e-6) {
double mid = (l + r) / 2;
if (mid * mid == num) return true;
else if (mid * mid > num) r = mid;
else l = mid;
}
int y = (int)(l + 1e-6);
if (y * y == num) return true;
return false;
}
};
标签:平方,return,int,mid,num,367,true,LeetCode
From: https://www.cnblogs.com/hjy94wo/p/16613888.html