231. Power of Two
EasyView on LeetCode
Time: O(1)
Space: O(1)
Advertisement
Intuition
A power of two in binary has exactly one bit set. The bit trick n & (n-1) clears the lowest set bit. If the result is 0 (and n > 0), only one bit was set -> n is a power of two.
Algorithm
- 1Return n > 0 && (n & (n - 1)) == 0.
Example Walkthrough
Input: n = 16
- 1.16 = 100002. n-1=15=011112. 16&15=0. Return true.
Output: true
Common Pitfalls
- •n must be positive - 0 satisfies n&(n-1)==0 but is not a power of two.
231.cs
C#
// Approach: Bit manipulation — a power of two has exactly one set bit in binary.
// Therefore: n > 0 AND (n & (n - 1)) == 0 is a sufficient and necessary condition.
// n & (n - 1) clears the lowest set bit; if the result is 0, only one bit was set.
// This O(1) trick avoids any loop or repeated division.
// Edge case: n <= 0 can never be a power of two, handled by the n > 0 check.
// Time: O(1) Space: O(1)
public class Solution
{
public bool IsPowerOfTwo(int n)
{
// Check if n is greater than 0 and if n AND (n-1) is 0
return n > 0 && (n & (n - 1)) == 0;
}
}Advertisement
Was this solution helpful?