自己写的:
class Solution {
public:
bool isPerfectSquare(int num) {
int l = 1, r = num;
while (l <= r)
{
int mid = l + (r - l) / 2;
if ((long long) mid * mid < num) l = mid + 1;
else if ((long long) mid * mid > num) r = mid - 1;
else return true;
}
return false;
}
};
这题应该不算难,比69.x的平方根简单。
不过看了官方代码,自己的代码还有改进空间(即不用写多次(long long) mid * mid
):
class Solution {
public:
bool isPerfectSquare(int num) {
int left = 0, right = num;
while (left <= right) {
int mid = (right - left) / 2 + left;
long square = (long) mid * mid;
if (square < num) {
left = mid + 1;
} else if (square > num) {
right = mid - 1;
} else {
return true;
}
}
return false;
}
};
标签:平方,return,int,mid,有效,while,num,367,false
From: https://www.cnblogs.com/hisun9/p/18526038