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 Code
< ? php function isPowerOfTwo ( $ n ) { return $ n && ( ! ( $ n & ( $ n - 1 ) ) ) ; } function findPosition ( $ n ) { if ( ! isPowerOfTwo ( $ n ) ) return -1 ; $ count = 0 ; while ( $ n ) { $ n = $ n >> 1 ; ++ $ count ; } return $ count ; } $ n = 0 ; $ pos = findPosition ( $ n ) ; if ( ( $ pos == -1 ) == true ) echo " n = " , ▁ $ n , ▁ " , " , STRNEWLINE TABSYMBOL TABSYMBOL " Invalid number " , ▁ " " ; STRNEWLINE else STRNEWLINE TABSYMBOL echo ▁ " n = " , ▁ $ n , ▁ " , " , STRNEWLINE TABSYMBOL TABSYMBOL " Position " , ▁ $ pos , ▁ " " $ n = 12 ; $ pos = findPosition ( $ n ) ; if ( ( $ pos == -1 ) == true ) echo " n = " , ▁ $ n , ▁ " , " , STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL " Invalid number " , ▁ " " ; STRNEWLINE else STRNEWLINE TABSYMBOL TABSYMBOL echo ▁ " n = " , ▁ $ n , STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL " Position " , ▁ $ pos , ▁ " " $ n = 128 ; $ pos = findPosition ( $ n ) ; if ( ( $ pos == -1 ) == true ) echo " n = " , ▁ $ n , ▁ " , " , STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL " Invalid number " , ▁ " " ; STRNEWLINE else STRNEWLINE TABSYMBOL TABSYMBOL echo ▁ " n = " , ▁ $ n , ▁ " , " , STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL " Position " , ▁ $ pos , ▁ " " ? >