AlgoInsight

DSA problem

Power of Two

EasyBit ManipulationPattern: Bit Trickstop600AmazonGoogleAppleMicrosoft

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 n == 2^x.

The elegant bit trick is that a positive power of two has exactly one set bit in its binary representation (for example 8 is 1000). Subtracting 1 from such a number flips that single bit to 0 and turns every lower bit to 1, so n & (n - 1) becomes 0 precisely when n is a power of two — provided n is positive.

Examples

Example 1
Input: n = 1
Output: true
Explanation: 1 equals 2^0, so it is a power of two.
Example 2
Input: n = 16
Output: true
Explanation: 16 equals 2^4. In binary 16 is 10000, which has exactly one set bit.
Example 3
Input: n = 3
Output: false
Explanation: 3 is 11 in binary with two set bits, so it is not a power of two.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bit-manipulationmathrecursion

Browse all DSA problems