Given two numbers N and K. The task is to find the index of the K-th set bit in the number from the right.
Note: Indexing in the binary representation starts from 0 from the right. For example in the binary number “000011”, the first set bit is at index 0 from right, and the second set bit is at index 1 from the right.
Input: N = 15, K = 3 Output: 2 15 is "1111", hence the third bit is at index 2 from right. Input: N = 19, K = 2 Output: 1 19 is "10011", hence the second set bit is at inex 1 from right.
Approach: Initialize a counter 0, and increase it if the last bit is set in the number. For accessing the next bit, right shift the number by 1. When the counter’s value is equal to K, then we return the index of the number which was being incremented on every right shift.
Below is the implementation of the above approach:
- Extract 'k' bits from a given position in a number.
- Position of rightmost different bit
- Position of rightmost set bit
- Modify a bit at a given position
- Find position of the only set bit
- Get the position of rightmost unset bit
- Check whether the bit at given position is set or unset
- Find the value at kth position in the generated array
- Position of rightmost bit with first carry in sum of two binary
- Position of rightmost common bit in two numbers
- Check whether the two numbers differ at one bit position only
- Find letter's position in Alphabet using Bit operation
- Find position of left most dis-similar bit for two numbers
- Python Slicing | Extract ‘k’ bits from a given position
- Count number of trailing zeros in Binary representation of a number using Bitset
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.