LeetCode 342: Power of Four Solution

Master LeetCode problem 342 (Power of Four), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

342. Power of Four

Problem Explanation

Explanation

To solve this problem without using loops/recursion, we can use two key observations:

  1. Any power of four must be a power of two as well.
  2. Any power of two in binary form has only one bit set to 1.

Based on these observations, we can create a mask where the only bit set to 1 is in an even position (starting from 0). By bitwise ANDing this mask with the given number, we can check if it is a power of four.

Solution Code

class Solution {
    public boolean isPowerOfFour(int n) {
        return n > 0 && (n & (n - 1)) == 0 && (n & 0x55555555) != 0;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 342 (Power of Four)?

This page provides optimized solutions for LeetCode problem 342 (Power of Four) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 342 (Power of Four)?

The time complexity for LeetCode 342 (Power of Four) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 342 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 342 in Java, C++, or Python.

Back to LeetCode Solutions