Check whether a number is a power of two / find the position of its only set bit
Problem
(1) Return true if n is a power of two. (2) If n has exactly one set bit, return that bit's position (counting from 1 at the rightmost bit); otherwise return −1.
Example 1
Input: n = 16 Output: power of two: true; position 5
Example 2
Input: n = 12 Output: false; −1
Also asked as: Program to find whether a no is power of two · Find position of the only set bit
Test cases
Case 1
Input: 16 Expected: 5
Case 2
Input: 12 Expected: -1
Case 3
Input: 1 Expected: 1
Case 4
Input: 0 Expected: -1
View solutionHide solution1 approach
1. n & (n − 1)
Time O(log n)Space O(1)
A power of two has exactly one set bit, so n & (n−1) clears it to 0. The bit position is log2(n), or count right shifts until you reach 1.
const isPowerOfTwo = (n) => n > 0 && (n & (n - 1)) === 0;
function onlySetBitPosition(n) { if (!isPowerOfTwo(n)) return -1; let pos = 1; while (!(n & 1)) { n >>= 1; pos++; } return pos; // 1-indexed}