SDE & MLE Prep

231. Power of Two

Problem

Decide whether the integer n is a power of two (2ˣ for some integer x ≥ 0).

Example: 16 → true; 3 → false; 1 → true

Constraints: follow-up: without loops or recursion.

A power of two has exactly one set bit: n > 0 and n & (n − 1) == 0.

Complexity: O(1).

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n > 0 and n & (n - 1) == 0