-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0367_valid_perfect_square.py
More file actions
51 lines (41 loc) · 1.25 KB
/
0367_valid_perfect_square.py
File metadata and controls
51 lines (41 loc) · 1.25 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
class Solution:
def isPerfectSquare(self, num: int) -> bool:
# Binary Search
left = 0
right = num
while (left <= right):
mid = left + (right - left) // 2
if (mid ** 2 == num):
return True
elif (mid ** 2 > num):
right = mid - 1
else:
left = mid + 1
return False
'''
# Newton's Law
r = num
# if num != 1
while (r * r > num):
r = (r + num / r) // 2
return r * r == num
'''
'''
# Linear Search
# 1 is a perfect square
if (num == 1):
return True
# 2 and 3 are not perfect square
if (num < 4):
return False
# Start from the beginning
if (num < (2 ** 31 - 1) // 2):
for i in range ((2 ** 31 - 1) // 2):
if (num < i ** 2):
return num == (i - 1) ** 2
# Start from the end
else:
for j in range (2 ** 31 - 1, (2 ** 31 - 1) // 2, -1):
if (num > j ** 2):
return num == (j + 1) ** 2
'''