Problem
Given an integern, return true if it is a power of four. Otherwise, return false.
An integer n is a power of four, if there exists an integer x such that n == 4^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 342 with 21 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 342 # by problem number
lcpy gen -s power_of_four # by problem name
n, return true if it is a power of four. Otherwise, return false.
An integer n is a power of four, if there exists an integer x such that n == 4^x.
Input: n = 16
Output: true
Input: n = 5
Output: false
Input: n = 1
Output: true
class Solution:
# Time: O(1)
# Space: O(1)
def is_power_of_four(self, n: int) -> bool:
# Power of two with the single set bit in an even (0-indexed) position:
# 4^x mod 3 == 1, while 2 * 4^x mod 3 == 2.
return n > 0 and n & (n - 1) == 0 and n % 3 == 1
| Time | Space |
|---|---|
| O(1) | O(1) |