LeetCode刷题实战367:有效的完全平方数
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.
示例
示例 1:
输入:num = 16
输出:true
示例 2:
输入:num = 14
输出:false
解题
class Solution {
public boolean isPerfectSquare(int num) {
if (num < 2) {
return true;
}
long left = 2, right = num / 2, x, guessSquared;
while (left <= right) {
x = left + (right - left) / 2;
guessSquared = x * x;
if (guessSquared == num) {
return true;
}
if (guessSquared > num) {
right = x - 1;
} else {
left = x + 1;
}
}
return false;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/valid-perfect-square/solution/you-xiao-de-wan-quan-ping-fang-shu-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public boolean isPerfectSquare(int num) {
if (num < 2) {
return true;
}
long left = 2, right = num / 2, x, guessSquared;
while (left <= right) {
x = left + (right - left) / 2;
guessSquared = x * x;
if (guessSquared == num) {
return true;
}
if (guessSquared > num) {
right = x - 1;
} else {
left = x + 1;
}
}
return false;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/valid-perfect-square/solution/you-xiao-de-wan-quan-ping-fang-shu-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。