-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path342 Power of Four.py
46 lines (38 loc) · 987 Bytes
/
342 Power of Four.py
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
"""
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
Author: Rajeev Ranjan
"""
class Solution(object):
def isPowerOfFour(self, num):
"""
Modular calculation
4^a mod 3
= (1)^a mod 3
= 1
:param num:
:return:
"""
if num < 1:
return False
if num & num -1 != 0:
return False
return num % 3 == 1
def isPowerOfFourNaive(self, num):
"""
Naive Determine number of 0 bits to be even
:type num: int
:rtype: bool
"""
if num < 1:
return False
if num & num-1 != 0:
return False
while True:
if num == 0:
return False
elif num == 1:
return True
num >>= 2