Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt
.
Example 1:
Input: 16 Returns: True
Example 2:
Input: 14 Returns: False
题意:给一个非负的整形,判断它是否为完全平方数
解法:使用二分法搜索,右界从num/2开始。还要注意数据类型溢出的问题
public class Solution {
public bool IsPerfectSquare(int num) {
long l = 1, r = num/2 + 1;
while (l <= r) {
long m = l + (r - l) / 2;
long pow = m * m;
if (pow == num) {
return true;
} else if (pow > num) {
r = m - 1;
} else if (pow < num) {
l = m + 1;
}
}
return false;
}
}