Problem 342

Abstract / Summary

Check if a number is a power of four by verifying it has exactly one bit set and that bit is in an even position.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0342.py

class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        if n == 0:
            return False
        for i in range(16): # 4^16 > 2^31
            if 4**i == n:
                return True
        return False
8 lines | 230 bytes | submitted August 13, 2023 | GitHub   12% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (2+ million submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
  • Math
  • Recursion
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method that determines whether a given integer is an exact power of four. It follows a straightforward procedural approach: it first eliminates the trivial non-positive case, then iterates through a bounded set of exponent values, comparing each computed power of four with the input. If a match is found, the method reports success; otherwise it concludes that the number is not a power of four.

Key Steps

The method begins with a guard clause that checks for the value zero. In this situation the function immediately returns False, because zero cannot be expressed as (4^k) for any integer exponent.

if n == 0:
    return False

Next, the algorithm enters a loop that iterates over a fixed range of exponent candidates. The range is chosen as 0 through 15 inclusive, based on the observation that (4^{16}) exceeds the maximum positive 32-bit signed integer (2^31 - 1). This bound guarantees that every possible power of four that fits in a standard 32-bit integer will be examined.

for i in range(16):  # 4^16 > 2^31
    if 4**i == n:
        return True

Inside the loop, the expression 4**i computes the current power of four using Python’s exponentiation operator. The result is compared directly to the input n. If equality is detected, the method returns True immediately, indicating that n is a power of four.

If the loop completes without finding a matching exponent, the method reaches its final statement, which returns False. This outcome signals that the input does not correspond to any power of four within the examined range.

return False

Edge Cases Handled

The explicit check for n == 0 addresses the edge case where the input is zero, a value that cannot satisfy the definition of a power of four. By returning False early, the function avoids unnecessary computation for this special case.

The loop’s upper bound of 16 is deliberately selected to cover the full spectrum of powers of four that can be represented in a 32-bit signed integer. This ensures that inputs such as 1 (4^0), 4 (4^1), 16 (4^2), and the largest representable power of four (4^15 = 1073741824) are all correctly identified. Values larger than 4^15 but still within the 32-bit range, such as 2^31 - 1, are safely excluded because they cannot be powers of four, and the loop terminates before reaching an exponent that would overflow the integer range.

Performance Optimizations

The early return for the zero case eliminates an entire iteration cycle for a common edge input, reducing unnecessary work.

Limiting the loop to a fixed count of sixteen iterations provides a deterministic execution path. Because the bound is derived from the maximum representable integer, the algorithm never performs more iterations than necessary to cover all valid candidates. This fixed-size loop avoids the overhead of dynamically calculating an upper bound during each call.

Using the built-in exponentiation operator (**) leverages Python’s optimized arithmetic routines, which are generally faster than manual multiplication inside a loop. The direct comparison 4**i == n allows the function to exit as soon as a match is found, preventing the evaluation of remaining exponent values.

Overall, the combination of an early guard clause, a tightly bounded loop, and immediate returns upon success yields a method that executes a predictable and minimal amount of work for any valid input.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big box of special number blocks. This code is like a little helper who checks if a number you give it belongs to a very specific pattern that happens when you keep multiplying the number four by itself.

First, the helper looks at the number you provided. If the number is zero, it knows right away that it is not part of this special group, so it stops looking.

Next, the helper starts a game of counting up to sixteen. For every step in that game, it does a little bit of math. It takes the number four and multiplies it by itself over and over again to see what happens. It compares that result to the number you gave at the start. If the math matches your number exactly, the helper is happy and knows it found a match. If it goes through all sixteen steps and still does not find your number, it quietly decides that your number does not fit the pattern.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 5 | μ = 5.54 | σ = 1.22

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# JS Go Rust TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
muhammadfarhankt Go
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
muhammadfarhankt Go
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
50 links | 33 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

13 solutions   August 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality