Determine if given number is a perfect square? Can't use Math.Sqrt library function | LeetCode Discuss
Read full article from Determine if given number is a perfect square? Can't use Math.Sqrt library function | LeetCode Discuss
Write a function that takes an integer as input and returns true if it's a perfect square else false.
public static bool IsPerfectSquare(int n)
{
}
ex: Perfect squares = 16 (4x4), 25 (5x5) etc
public static bool IsPerfectSquare(int n)
{
}
ex: Perfect squares = 16 (4x4), 25 (5x5) etc
public boolean IsPerfectSquare(long n)
{
if (n <= 0)
return false;
if (n == 1)
return true;
long l = 1;
long r = n;
while (l <= r) {
long mid = l + (r - l )/2;
long square = mid * mid;
if (square == n) {
return true;
} else if (square > n) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return false;
}