ID | Title | Difficulty | |
---|---|---|---|
Loading... |
367. Valid Perfect Square
Easy
LeetCode
Math, Binary Search
Problem
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.
Example 1:
Input: num = 16
Output: true
Example 2:
Input: num = 14
Output: false
Code
class Solution {
public boolean isPerfectSquare(int num) {
long left = 1;
long right = num / 2;
while(left + 1 < right) {
long mid = (left + right) / 2;
if(mid * mid == num) return true;
if(mid * mid > num) {
right = mid;
} else {
left = mid;
}
}
if(left * left == num) return true;
if(right * right == num) return true;
return false;
}
}
按 <- 键看上一题!
366. Find Leaves of Binary Tree
按 -> 键看下一题!
368. Largest Divisible Subset