LeetCode 367. Valid Perfect Square

题目

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 as sqrt.

Example 1:

1
2
Input: 16
Output: true

Example 2:

1
2
Input: 14
Output: false

思路

Easy题打卡。二分查找,理论上最快的方法貌似是牛顿迭代

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution(object):
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
left, right = 0, 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