File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ Check if an integer is a power of three.
3+
4+ Time Complexity: O(log₃ n)
5+ Space Complexity: O(1)
6+ """
7+
8+ def is_power_of_three(n: int) -> bool:
9+ """Return True if n is a power of three (n > 0).
10+
11+ >>> is_power_of_three(1)
12+ True
13+ >>> is_power_of_three(3)
14+ True
15+ >>> is_power_of_three(9)
16+ True
17+ >>> is_power_of_three(27)
18+ True
19+ >>> is_power_of_three(2)
20+ False
21+ >>> is_power_of_three(0)
22+ False
23+ >>> is_power_of_three(-3)
24+ False
25+ >>> is_power_of_three(81)
26+ True
27+ """
28+ if not isinstance(n, int):
29+ raise TypeError("n must be an integer")
30+ if n <= 0:
31+ return False
32+ while n % 3 == 0:
33+ n //= 3
34+ return n == 1
35+
36+
37+ if __name__ == "__main__":
38+ import doctest
39+ doctest.testmod()
You can’t perform that action at this time.
0 commit comments