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:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Extract 'k' bits from a given position in a number.
- Position of rightmost different bit
- Position of rightmost set bit
- Find position of the only set bit
- Modify a bit at a given position
- Check whether the bit at given position is set or unset
- Get the position of rightmost unset bit
- Check whether the two numbers differ at one bit position only
- Find the value at kth position in the generated array
- Position of rightmost common bit in two numbers
- Position of rightmost bit with first carry in sum of two binary
- Find letter's position in Alphabet using Bit operation
- Python Slicing | Extract ‘k’ bits from a given position
- Find position of left most dis-similar bit for two numbers
- Find position of given term in a series formed with only digits 4 and 7 allowed
- Microsoft Interview Experience for full time position of Software Engineer at Bangalore
- Find the largest number smaller than integer N with maximum number of set bits
- Maximize a given unsigned number number by swapping bits at it's extreme positions.
- Count number of trailing zeros in Binary representation of a number using Bitset
- Find a number which give minimum sum when XOR with every number of array of integers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.