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
def isPowerOfTwo ( n ) : NEW_LINE INDENT return ( n and ( not ( n & ( n - 1 ) ) ) ) NEW_LINE DEDENT def findPosition ( n ) : NEW_LINE INDENT if not isPowerOfTwo ( n ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT n = n >> 1 NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 0 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 DEDENT