231. Power of Two LeetCode Solution

In this guide, you will get 231. Power of Two LeetCode Solution with the best time and space complexity. The solution to Power of Two problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Power of Two solution in C++
  4. Power of Two solution in Java
  5. Power of Two solution in Python
  6. Additional Resources
231. Power of Two LeetCode Solution image

Problem Statement of Power of Two

Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2x.

Example 1:

Input: n = 1
Output: true
Explanation: 20 = 1

Example 2:

Input: n = 16
Output: true
Explanation: 24 = 16

Example 3:

Input: n = 3
Output: false

Constraints:

-231 <= n <= 231 – 1

Follow up: Could you solve it without loops/recursion?

Complexity Analysis

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

231. Power of Two LeetCode Solution in C++

class Solution {
 public:
  bool isPowerOfTwo(int n) {
    return n >= 0 && __builtin_popcount(n) == 1;
  }
};
/* code provided by PROGIEZ */

231. Power of Two LeetCode Solution in Java

class Solution {
  public boolean isPowerOfTwo(int n) {
    return n >= 0 && Integer.bitCount(n) == 1;
  }
}
// code provided by PROGIEZ

231. Power of Two LeetCode Solution in Python

class Solution:
  def isPowerOfTwo(self, n: int) -> bool:
    return n >= 0 and n.bit_count() == 1
# code by PROGIEZ

Additional Resources

See also  8. String to Integer (atoi) LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.