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
题意:
验证完全平方数
思路:
二分查找,可回顾之前[leetcode]278. First Bad Version首个坏版本 笔记
需要注意的是类型声明为long
代码:
class Solution {
public boolean isPerfectSquare(int num) {
long left = 0;
long right = num; while (left <= right) {
long mid = left + (right - left) / 2;
if (mid * mid == num) {
return true;
} else if (mid * mid < num) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
}