- Related Questions & Answers
- Position of rightmost set bit in C++
- Find position of the only set bit in C++
- Golang program to turn off the k’th bit in a number.
- Golang Program to turn on the k’th bit in a number.
- Check whether K-th bit is set or nots in Python
- K’th Boom Number in C++
- Golang program to check if k’th bit is set for a given number or not.
- Update the bit in the given position or Index of a number using C++
- Minimum Number of K Consecutive Bit Flips in C++
- Find most significant set bit of a number in C++
- k-th prime factor of a given number in java
- Position of rightmost different bit in C++
- Golang Program to find the position of the rightmost set bit
- Set the bit at a specific position in the BitArray to the specified value in C#?
- Find k-th character of decrypted string - Set – 2 in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this problem, we are given two integers N and K. Our task is to find the index of K^{th} set a bit of the number N, counted from right.

Set bits are checked from the binary representation of the number. The indexing in binary representation starts from index 0 from the right direction and propagates towards left.

**Example** − in the binary number ‘011101’, at index 0 from right we have 1, at index 1 from right we have 0, and so on.

Now, let’s take an example to understand the problem

**Input** − N = 6, K = 2

**Output** − 2

**Explanation** − The binary representation of 6 is 0110. The 2nd set bit from the right will be at index 2.

To solve this problem, we will have to check if the current bit is set, if it is then we will decrease the value of K. After every check, we will shift the number bt 1, this will give the next bit, also we will maintain the number of shifts done. Once the value of K becomes 0, we will print the count of shifts done.

Program to show the implementation of our logic

#include <iostream> using namespace std; int FindIndexKthBit(int N, int K) { int index=0; while (N) { if (N & 1) K--; if (!K) return index; index++; N = N >> 1; } return -1; } int main() { int N = 12, K = 2; cout<<"The "<<K<<"th set bit of the number "<<N<<" is at index : \t"; int index = FindIndexKthBit(N, K); if (index!=-1) cout<<index; else cout<<"\nsorry no index found"; return 0; }

The 2th set bit of the number 12 is at index : 3

Advertisements