leetcode367:有效的完全平方数

思想:

1.定义变量l和h,存放中间变量

2.将l加h整除2等于mid,然后算出mid的平方t,最后比较t和num的大小。

3.若t<num,l等于mid+1;若t>num,h等于mid-1;若t=num,返回True

4.直到循环结束,返回False

class Solution:
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        l=1
        h=num
        while l<=h:
            mid=(l+h)//2
            t=mid**2
            if t<num:
                l=mid+1
            elif t>num:
                h=mid-1
            else:
                return True
        return False

猜你喜欢

转载自blog.csdn.net/weixin_43160613/article/details/84171586