Position of the K | Java 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
import java . util . * ; class GFG { static int FindIndexKthBit ( int n , int k ) { int cnt = 0 ; int ind = 0 ; while ( n > 0 ) { if ( ( n & 1 ) != 0 ) cnt ++ ; if ( cnt == k ) return ind ; ind ++ ; n = n >> 1 ; } return - 1 ; } public static void main ( String args [ ] ) { int n = 15 , k = 3 ; int ans = FindIndexKthBit ( n , k ) ; if ( ans != - 1 ) System . out . println ( ans ) ; else System . out . println ( " No ▁ k - th ▁ set ▁ bit " ) ; } }