Leetcode•Apr 02, 2025

367 Valid Perfect Square

Hazrat Ali

Leetcode

Given a positive integer num, return true if num is a perfect square or false otherwise.

A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself.

You must not use any built-in library function, such as sqrt.

Example 1:

Input: num = 16
Output: true
Explanation: We return true because 4 * 4 = 16 and 4 is an integer.

Example 2:

Input: num = 14
Output: false
Explanation: We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer.


* Valid Perfect Square
 *
 * Given a positive integer num, write a function which returns True if num is a perfect square else False.
 *
 * Note: Do not use any built-in library function such as sqrt.
 *
 * Example 1:
 *
 * Input: 16
 * Output: true
 * Example 2:
 *
 * Input: 14
 * Output: false
 
 
Solution 
 
/**
 * @param {number} num
 * @return {boolean}
 */
const isPerfectSquare = num => {
  let lo = 0;
  let hi = num;

  while (lo <= hi) {
    const mid = (lo + hi) >>> 1;

    if (mid * mid === num) {
      return true;
    } else if (mid * mid < num) {
      lo = mid + 1;
    } else {
      hi = mid - 1;
    }
  }

  return false;
};



Comments