Find position of the only set bit | C ++ program to find position of only set bit in a given number ; A utility function to check whether n is a power of 2 or not . goo . gl / 17 Arj See http : ; Returns position of the only set bit in ' n ' ; Iterate through bits of n till we find a set bit i & n will be non - zero only when ' i ' and ' n ' have a set bit at same position ; Unset current bit and set the next bit in ' i ' ; increment position ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isPowerOfTwo ( unsigned n ) { return n && ( ! ( n & ( n - 1 ) ) ) ; } int findPosition ( unsigned n ) { if ( ! isPowerOfTwo ( n ) ) return -1 ; unsigned i = 1 , pos = 1 ; while ( ! ( i & n ) ) { i = i << 1 ; ++ pos ; } return pos ; } int main ( void ) { int n = 16 ; int pos = findPosition ( n ) ; ( pos == -1 ) ? cout << " n ▁ = ▁ " << n << " , ▁ Invalid ▁ number " << endl : cout << " n ▁ = ▁ " << n << " , ▁ Position ▁ " << pos << endl ; n = 12 ; pos = findPosition ( n ) ; ( pos == -1 ) ? cout << " n ▁ = ▁ " << n << " , ▁ Invalid ▁ number " << endl : cout << " n ▁ = ▁ " << n << " , ▁ Position ▁ " << pos << endl ; n = 128 ; pos = findPosition ( n ) ; ( pos == -1 ) ? cout << " n ▁ = ▁ " << n << " , ▁ Invalid ▁ number " << endl : cout << " n ▁ = ▁ " << n << " , ▁ Position ▁ " << pos << endl ; return 0 ; }