Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created August 9, 2025 22:39
Show Gist options
  • Save Ifihan/070409a35f1ff854115fbf54974a334e to your computer and use it in GitHub Desktop.
Save Ifihan/070409a35f1ff854115fbf54974a334e to your computer and use it in GitHub Desktop.
Power of Two

Question

Approach

I used a bitwise trick. A number is a power of two if:

  • It is positive.
  • It has exactly one bit set in its binary representation.

The property (n & (n - 1)) == 0 checks this, because subtracting 1 from a power of two flips the single 1 bit to 0 and sets all lower bits to 1, so the bitwise AND becomes 0. For any number that isn’t a power of two, this condition fails.

Implementation

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

Complexities

  • Time: O(1)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment