Position of the K-th set bit in a number in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two integers N and K. Our task is to find the index of Kth 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.

Example

Program to show the implementation of our logic

 Live Demo

#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;
}

Output

The 2th set bit of the number 12 is at index : 3
raja
Published on 17-Apr-2020 07:57:45
Advertisements