Position of the K | Function that returns the Kth set bit ; Traverse in the binary ; Check if the last bit is set or not ; Check if count is equal to k then return the index ; Increase the index as we move right ; Right shift the number by 1 ; Driver Code
def FindIndexKthBit ( n , k ) : NEW_LINE INDENT cnt , ind = 0 , 0 NEW_LINE while n > 0 : NEW_LINE INDENT if n & 1 : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT if cnt == k : NEW_LINE INDENT return ind NEW_LINE DEDENT ind += 1 NEW_LINE n = n >> 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , k = 15 , 3 NEW_LINE ans = FindIndexKthBit ( n , k ) NEW_LINE if ans != - 1 : NEW_LINE INDENT print ( ans ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ k - th ▁ set ▁ bit " ) NEW_LINE DEDENT DEDENT