Power of Two
Master this topic with zero to advance depth.
Power of Two
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two if there exists an integer x such that .
Examples
Input: n = 1
Output: true
Input: n = 16
Output: true
Input: n = 3
Output: false
Approach 1
Level I: Brute Force (Division)
Intuition
Keep dividing the number by 2 until it hits 1. If at any point the remainder is not 0, it's not a power of two.
⏱ $O(\\log N)$💾 $O(1)$
Approach 2
Level II: Math (Max Power of Two)
Intuition
Since the input is a 32-bit signed integer, the largest power of two is . If n is a power of two, it must be a divisor of .
⏱ $O(1)$💾 $O(1)$
Approach 3
Level III: Optimal (Bit Manipulation)
Intuition
A power of two in binary has exactly one bit set. The expression n & (n - 1) clears the rightmost set bit. If n is a power of two, clearing its only set bit should result in 0.
⏱ $O(1)$💾 $O(1)$
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.