Find position of the only set bit | A utility function to check whether n is power of 2 or not . ; 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 Code
function isPowerOfTwo ( n ) { return ( n > 0 && ( ( n & ( n - 1 ) ) == 0 ) ) ? true : false ; } function findPosition ( n ) { if ( isPowerOfTwo ( n ) == false ) return - 1 ; var i = 1 ; var pos = 1 ; while ( ( i & n ) == 0 ) { i = i << 1 ; pos += 1 ; } return pos ; } var n = 16 ; var pos = findPosition ( n ) ; if ( pos == - 1 ) document . write ( " " + n + " " ) ; else document . write ( " " + n + " " + pos ) ; document . write ( " " ) ; n = 12 ; pos = findPosition ( n ) ; if ( pos == - 1 ) document . write ( " " + n + " " ) ; else document . write ( " " + n + " " , pos ) ; document . write ( " " ) ; n = 128 ; pos = findPosition ( n ) ; if ( pos == - 1 ) document . write ( " " + n + " " ) ; else document . write ( " " + n + " " + pos ) ;