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 ' ; One by one move the only set bit to right till it reaches end ; increment count of shifts ; Driver program to test above function
function isPowerOfTwo ( n ) { return ( n && ( ! ( n & ( n - 1 ) ) ) ) } function findPosition ( n ) { if ( ! isPowerOfTwo ( n ) ) return - 1 var count = 0 while ( n ) { n = n >> 1 count += 1 } return count } var n = 0 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 ) document . write ( " " )