Problem Description
Given an integer n, determine if it is a power of two. In other words, check if there exists an integer x such that n == 2^x. For instance, if n = 16 then return true (since 2^4 = 16) and if n = 3 then return false.
Key Insights
- A power of two in binary representation contains exactly one set bit.
- Negative numbers and zero cannot be powers of two.
- The bit manipulation trick n & (n - 1) can be used to determine if there's exactly one set bit (for n > 0).
Space and Time Complexity
Time Complexity: O(1)
Space Complexity: O(1)
Solution
The algorithm checks whether n is a power of two by leveraging the fact that powers of two have exactly one set bit. First, the check n > 0 ensures the number is positive because only positive numbers can be powers of two. Then, by performing n & (n - 1), we verify that the number has only one set bit. If the result is 0, then n is a power of two; otherwise, it is not. This solution executes in constant time and uses constant space.