Skip to content

Commit c8f6f79

Browse files
Power of 4 (TheAlgorithms#9505)
* added power_of_4 * updated power_of_4 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * updated power_of_4 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * updated power_of_4 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * updated power_of_4 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * updated power_of_4 * added type check * added tescase --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent e7a59bf commit c8f6f79

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

bit_manipulation/power_of_4.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
3+
Task:
4+
Given a positive int number. Return True if this number is power of 4
5+
or False otherwise.
6+
7+
Implementation notes: Use bit manipulation.
8+
For example if the number is the power of 2 it's bits representation:
9+
n = 0..100..00
10+
n - 1 = 0..011..11
11+
12+
n & (n - 1) - no intersections = 0
13+
If the number is a power of 4 then it should be a power of 2
14+
and the set bit should be at an odd position.
15+
"""
16+
17+
18+
def power_of_4(number: int) -> bool:
19+
"""
20+
Return True if this number is power of 4 or False otherwise.
21+
22+
>>> power_of_4(0)
23+
Traceback (most recent call last):
24+
...
25+
ValueError: number must be positive
26+
>>> power_of_4(1)
27+
True
28+
>>> power_of_4(2)
29+
False
30+
>>> power_of_4(4)
31+
True
32+
>>> power_of_4(6)
33+
False
34+
>>> power_of_4(8)
35+
False
36+
>>> power_of_4(17)
37+
False
38+
>>> power_of_4(64)
39+
True
40+
>>> power_of_4(-1)
41+
Traceback (most recent call last):
42+
...
43+
ValueError: number must be positive
44+
>>> power_of_4(1.2)
45+
Traceback (most recent call last):
46+
...
47+
TypeError: number must be an integer
48+
49+
"""
50+
if not isinstance(number, int):
51+
raise TypeError("number must be an integer")
52+
if number <= 0:
53+
raise ValueError("number must be positive")
54+
if number & (number - 1) == 0:
55+
c = 0
56+
while number:
57+
c += 1
58+
number >>= 1
59+
return c % 2 == 1
60+
else:
61+
return False
62+
63+
64+
if __name__ == "__main__":
65+
import doctest
66+
67+
doctest.testmod()

0 commit comments

Comments
 (0)