题目地址:367. 有效的完全平方数 - 力扣(LeetCode)
bool isPerfectSquare(int num) {
if (num == 1) return true;
int left = 2, right = (num / 2) + 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if ((mid * mid) < num) {
left = mid + 1;
}
else if ((mid * mid) > num) right = mid - 1;
else return true;
}
return false;
}
测试函数:
void main() {
printf("%d", isPerfectSquare(4));
}
python版本:
class Solution:
def isPerfectSquare(self, num: int) -> bool:
if num == 1: return True
left = 2
right = int(num/2) + 1
while(left <= right):
mid = left + int((right - left) / 2)
if (mid * mid < num): left = mid + 1
elif (mid * mid > num): right = mid - 1
else: return True
return False