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
def isPowerOfTwo ( n ) : NEW_LINE INDENT return ( True if ( n > 0 and ( ( n & ( n - 1 ) ) > 0 ) ) else False ) ; NEW_LINE DEDENT def findPosition ( n ) : NEW_LINE INDENT if ( isPowerOfTwo ( n ) == True ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT i = 1 ; NEW_LINE pos = 1 ; NEW_LINE while ( ( i & n ) == 0 ) : NEW_LINE INDENT i = i << 1 ; NEW_LINE pos += 1 ; NEW_LINE DEDENT return pos ; NEW_LINE DEDENT n = 16 ; NEW_LINE pos = findPosition ( n ) ; NEW_LINE if ( pos == - 1 ) : NEW_LINE INDENT print ( " n ▁ = " , n , " , ▁ Invalid ▁ number " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " n ▁ = " , n , " , ▁ Position ▁ " , pos ) ; NEW_LINE DEDENT n = 12 ; NEW_LINE pos = findPosition ( n ) ; NEW_LINE if ( pos == - 1 ) : NEW_LINE INDENT print ( " n ▁ = " , n , " , ▁ Invalid ▁ number " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " n ▁ = " , n , " , ▁ Position ▁ " , pos ) ; NEW_LINE DEDENT n = 128 ; NEW_LINE pos = findPosition ( n ) ; NEW_LINE if ( pos == - 1 ) : NEW_LINE INDENT print ( " n ▁ = " , n , " , ▁ Invalid ▁ number " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " n ▁ = " , n , " , ▁ Position ▁ " , pos ) ; NEW_LINE DEDENT