Position of the K | C ++ program to implement the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int FindIndexKthBit ( int n , int k ) { int cnt = 0 ; int ind = 0 ; while ( n ) { if ( n & 1 ) cnt ++ ; if ( cnt == k ) return ind ; ind ++ ; n = n >> 1 ; } return -1 ; } int main ( ) { int n = 15 , k = 3 ; int ans = FindIndexKthBit ( n , k ) ; if ( ans != -1 ) cout << ans ; else cout << " No ▁ k - th ▁ set ▁ bit " ; return 0 ; }