367. Valid Perfect Square
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
Constraints:
1 <= num <= 2^31 - 1
Solution:
Bruteforce Solution: Time complexity is O(sqrt(n)).
class Solution {
public boolean isPerfectSquare(int num) {
long y=0;
while(y*y<=num)
{
if(y*y==num)
return true;
y++;
}
return false;
}
}
Efficient Solution Using binary search: Time complexity is O(Log(sqrt(n))).
class Solution {
public boolean isPerfectSquare(int num) {
long start=0;
long end=num/2;
while(start<=end)
{
long mid=start+(end-start)/2;
if(num==1)
{
return true;
}
if(mid*mid==num)
{
return true;
}
else if(mid*mid<num)
{
start=mid+1;
}
else
end=mid-1;
}
return false;
}
}
Also read:
0 Comments