Skip to content

Commit bafc1bf

Browse files
authored
Create valid-perfect-square.py
1 parent c9babbf commit bafc1bf

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Python/valid-perfect-square.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(logn)
2+
# Space: O(1)
3+
4+
# Given a positive integer num, write a function
5+
# which returns True if num is a perfect square else False.
6+
#
7+
# Note: Do not use any built-in library function such as sqrt.
8+
#
9+
# Example 1:
10+
#
11+
# Input: 16
12+
# Returns: True
13+
# Example 2:
14+
#
15+
# Input: 14
16+
# Returns: False
17+
18+
class Solution(object):
19+
def isPerfectSquare(self, num):
20+
"""
21+
:type num: int
22+
:rtype: bool
23+
"""
24+
left, right = 1, num
25+
while left <= right:
26+
mid = left + (right - left) / 2
27+
if mid >= num / mid:
28+
right = mid - 1
29+
else:
30+
left = mid + 1
31+
return left == num / left and num % left == 0

0 commit comments

Comments
 (0)