Problem
Given an integern, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == 3^x.
Examples
Constraints
- -2^31 <= n <= 2^31 - 1
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 326 with 20 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 326 # by problem number
lcpy gen -s power_of_three # by problem name
n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == 3^x.
Input: n = 27
Output: true
Explanation: 27 = 3^3
Input: n = 0
Output: false
Explanation: There is no x where 3^x = 0.
Input: n = -1
Output: false
Explanation: There is no x where 3^x = (-1).
class Solution:
# Time: O(1)
# Space: O(1)
def is_power_of_three(self, n: int) -> bool:
# 3^19 = 1162261467 is the largest power of three fitting in a signed
# 32-bit int; it is divisible by every smaller power of three and by
# no other positive integer in range. Constant time, no loops.
return n > 0 and 1162261467 % n == 0
| Time | Space |
|---|---|
| O(1) | O(1) |