Find position of the only set bit | A utility function to check whether n is power of 2 or goo . gl / 17 Arj not . 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 Code
< ? php function isPowerOfTwo ( $ n ) { return $ n && ( ! ( $ n & ( $ n - 1 ) ) ) ; } function findPosition ( $ n ) { if ( ! isPowerOfTwo ( $ n ) ) return -1 ; $ i = 1 ; $ pos = 1 ; while ( ! ( $ i & $ n ) ) { $ i = $ i << 1 ; ++ $ pos ; } return $ pos ; } $ n = 16 ; $ 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 = 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 , ▁ " " ? >