-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0367_valid_perfect_square.py
More file actions
54 lines (40 loc) · 1.08 KB
/
0367_valid_perfect_square.py
File metadata and controls
54 lines (40 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'''
367. Valid Perfect Square
Easy
Given a positive integer num, write a function which
returns True if num is a perfect square else False.
Follow up: Do not use any built-in library function such as sqrt.
Example 1:
Input: num = 16
Output: true
Example 2:
Input: num = 14
Output: false
Constraints:
1 <= num <= 2^31 - 1
'''
class Solution:
def isPerfectSquare(self, num: int) -> bool:
if num == 1:
return True
left = 0
right = num
med = right - (right-left) // 2
while left < right:
expected = med * med
if expected == num:
break
if expected > num:
right = med
else:
left = med
med = right - (right-left) // 2
if left == med or right == med:
break
return med * med == num
sol = Solution()
assert sol.isPerfectSquare(16) is True
assert sol.isPerfectSquare(14) is False
assert sol.isPerfectSquare(1) is True
assert sol.isPerfectSquare(2) is False
assert sol.isPerfectSquare(9) is True