给定一个 正整数 num
,编写一个函数,如果 num
是一个完全平方数,则返回 true
,否则返回 false
。
进阶:不要 使用任何内置的库函数,如 sqrt
。
示例 1:
输入:num = 16 输出:true
示例 2:
输入:num = 14 输出:false
提示:
1 <= num <= 2^31 - 1
二分法。
class Solution:
def isPerfectSquare(self, num: int) -> bool:
left, right = 1, num
while left < right:
mid = left + ((right - left) >> 1)
if num // mid <= mid:
right = mid
else:
left = mid + 1
return left * left == num
class Solution {
public boolean isPerfectSquare(int num) {
int left = 1, right = num;
while (left < right) {
int mid = (left + right) >>> 1;
if (num / mid <= mid) {
right = mid;
} else {
left = mid + 1;
}
}
return left * left == num;
}
}
class Solution {
public:
bool isPerfectSquare(int num) {
long left = 1, right = num;
while (left < right) {
int mid = left + ((right - left) >> 1);
if (num / mid <= mid) {
right = mid;
} else {
left = mid + 1;
}
}
return left * left == num;
}
};
func isPerfectSquare(num int) bool {
left, right := 1, num
for left < right {
mid := left + (right-left)>>1
if num/mid <= mid {
right = mid
} else {
left = mid + 1
}
}
return left*left == num
}