Exercise 11: Check if Number is Perfect Square
Problem Statement
Create a function `isPerfectSquare(n)` that checks if number is perfect square.
Example:
- isPerfectSquare(16) → true
- isPerfectSquare(15) → false
Sample Output:
isPerfectSquare(16) => true isPerfectSquare(15) => false isPerfectSquare(0) => true
Solution
const isPerfectSquare = (n) => {
const num = Number(n);
if (!Number.isFinite(num) || num < 0) return false;
const sqrt = Math.sqrt(num);
return Number.isInteger(sqrt);
};Explanation
Overall Goal:
- Number perfect square hai ya nahi check karna.
Line 1: Function header
const isPerfectSquare = (n) => {
Line 2: Convert
const num = Number(n);
Line 3: Validation
if (!Number.isFinite(num) || num < 0) return false;
Line 4: Square root
const sqrt = Math.sqrt(num);
Line 5: Check integer
return Number.isInteger(sqrt);
Real world:
- Math problems: perfect square checks.
- Algorithms: optimization problems.