Skip to content

231. Power of Two #2031

Answered by mah-shamim
mah-shamim asked this question in Q&A
Aug 9, 2025 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

We need to determine if a given integer n is a power of two. A number is considered a power of two if it can be expressed as 2^x where x is a non-negative integer. The solution should efficiently check this condition without using loops or recursion.

Approach

The approach leverages bit manipulation properties of numbers that are powers of two. Here's the key insight:

  • Positive Check: Negative numbers and zero cannot be powers of two, so we immediately return false for these cases.
  • Bit Manipulation: For positive numbers, a power of two in binary representation has exactly one '1' bit, with all other bits being '0'. For example:
    • 20 = 11 in binary.
    • 21 = 210 in binary.
    • 22 = 4100 in …

Replies: 1 comment 2 replies

Comment options

mah-shamim
Aug 9, 2025
Maintainer Author

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Aug 9, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Aug 9, 2025
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants