给一个正整数num,写一个函数判断它是否是一个完全的平方数,是则返回True,不是返回False
注意:不要使用任何内嵌的函数,如sqrt
Example 1:
Input: 16 Output: trueExample 2:
Input: 14 Output: false
1:二分法
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
low = 1
high = num
while low < high:
mid = (low + high) // 2
if mid * mid == num:
return True
elif mid * mid < num:
low = mid + 1
else:
high = mid - 1
return low * low == num
算法题来自:https://leetcode-cn.com/problems/valid-perfect-square/description/