LeetCode 367. Valid Perfect Square

Post by ailswan Dec. 13, 2023

367. Valid Perfect Square

Problem Statement

link: LeetCode.cn 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:

Input: num = 16 Output: true

Input: num = 14 Output: false

Solution Approach

Algorithm

Implement

    class Solution:
    def isPerfectSquare(self, num: int) -> bool:
      l, r = 0, num
      while l <= r:
        m = (l + r) // 2
        t = m * m
        if t == nums:
          return True
        if t < num:
          l = m + 1
        else: 
          r = m - 1
      return False