367. Valid Perfect Square
1. Question
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Follow up: Do not use any built-in library function such as sqrt
.
2. Examples
Example 1:
Input: num = 16
Output: true
Example 2:
Input: num = 14
Output: false
3. Constraints
1 <= num <= 2^31 - 1
4. References
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-perfect-square 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
5. Solutions
5.1. 使用工具类
class Solution {
public boolean isPerfectSquare(int num) {
int k = (int)Math.sqrt(num);
return k * k == num;
}
}
5.2. 二分查找
class Solution {
public boolean isPerfectSquare(int num) {
int left = 1;
int right = num;
while (left <= right) {
int mid = (left + right) / 2;
long res = (long) mid * mid;
if (res < num) {
left = mid + 1;
} else if (res > num) {
right = mid - 1;
} else {
return true;
}
}
return false;
}
}