這題是用來求一個數是不是另一個數的平方。用二分法可以輕松解決。每次看中間的數的平方與之比較,大了,則中間數為新的list的上限,反之亦然。
class Solution(object):
def __init__(self):
self.list1 = []
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
if num == or num == :
return True
if num < :
return False
if self.list1 == []:
self.list1 = [, int(num/)]
middle = int((self.list1[] + self.list1[-])/)
if middle ** == num:
return True
elif middle ** < num:
self.list1 = [middle, self.list1[-]]
else:
self.list1 = [self.list1[], middle]
if self.list1[] >= self.list1[-] - :
return False
else:
return self.isPerfectSquare(num)