LeetCode 231: Power of Two Solution

Master LeetCode problem 231 (Power of Two), 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.

231. Power of Two

Problem Explanation

Explanation

To determine if an integer is a power of two, we can check if there is only one bit set in its binary representation. If there is exactly one bit set, then the number is a power of two. We can achieve this by performing a bitwise AND operation between the number and its predecessor i.e., n & (n-1). If the result is 0, then the number is a power of two.

  • Time complexity: O(1)
  • Space complexity: O(1)

Solution Code

class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n <= 0) {
            return false;
        }
        return (n & (n - 1)) == 0;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 231 (Power of Two)?

This page provides optimized solutions for LeetCode problem 231 (Power of Two) 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 231 (Power of Two)?

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

Can I run code for LeetCode 231 on DevExCode?

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

Back to LeetCode Solutions