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 assqrt.
Example 1:
Input: 16
Returns: True
Example 2:
Input: 14
Returns: False
Binary Search
class Solution(object):
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
left = 0
right = num
while left <= right:
mid = (left + right)/2
if mid*mid == num:
return True
elif mid*mid < num:
left = mid +1
else:
right = mid -1
return False
二刷:
class Solution(object):
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
start, end = 1, num
while start +1 < end:
mid = (start+end)/2
if mid*mid < num:
start = mid
else:
end = mid
if start*start == num or end*end == num:
return True
return False