LeetCode 367 Valid Perfect Square (Python)

Posted by 小明MaxMing on May 9, 2020

题目

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.

解题思路

二分搜索n,使得num = n * n

代码

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

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅