Position of the Okay-th set bit in a quantity

Given two numbers N and Okay. The activity is to search out the index of the Okay-th set bit within the quantity from the precise.

Note: Indexing within the binary illustration begins from zero from the precise. For instance within the binary quantity “000011”, the primary set bit is at index zero from proper, and second set bit is at index 1 from proper.

Examples:

Input: N = 15, Okay = three
Output: 2
15 is “1111”, therefore the third bit is at index 2 from proper.

Input: N = 19, Okay = 2
Output: 1
19 is “10011”, therefore the second set bit is at inex 1 from proper.

Approach: Initialize a counter zero, and improve it if the final bit is ready within the quantity. For accessing the subsequent bit, proper shift the quantity by 1. When the counter’s worth is the same as Okay, then we return the index of the quantity which was being incremented on each proper shift.

Below is the implementation of the above method:

#embody

utilizing namespace std;

  

int FindIndexKthBit(int n, int ok)

    int cnt = zero;

    int ind = zero;

  

    

    whereas (n)

  

    return -1;

  

int most important()

Striver(underscore)79 at Codechef and codeforces D

If you want GeeksforGeeks and want to contribute, you can too write an article utilizing contribute.geeksforgeeks.org or mail your article to [email protected] See your article showing on the GeeksforGeeks most important web page and assist different Geeks.

Please Improve this text for those who discover something incorrect by clicking on the “Improve Article” button under.

Article Tags :

thumb_up
Be the First to upvote.

Please write to us at [email protected] to report any concern with the above content material.

Post navigation

Previous

first_page Minimum worth amongst AND of parts of each subset of an array

Share this put up!