给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
注意:不要使用任何内置的库函数,如 sqrt
。
示例 1:
输入: 16 输出: True
示例 2:
输入: 14 输出: False
python 与求一个数的平方根类似
class Solution(object):
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
left=0;right=num
while left<right:
mid=(left+right)//2
if num<mid**2:
right=mid
else:
left=mid+1
if left>1:
sqrt_num=left-1
else:
sqrt_num=left
return sqrt_num**2==num
