- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Position of the K-th set bit in a number in C++
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
#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
- Related Articles
- Position of rightmost set bit in C++
- Check whether K-th bit is set or nots in Python
- Find position of the only set bit in C++
- Find value of k-th bit in binary representation in C++
- Minimum Number of K Consecutive Bit Flips in C++
- Update the bit in the given position or Index of a number using C++
- Find most significant set bit of a number in C++
- Find k-th character of decrypted string - Set – 2 in C++
- Find the k-th smallest divisor of a natural number N in C++
- Set the bit at a specific position in the BitArray to the specified value in C#?
- Find k-th bit in a binary string created by repeated invert and append operations in C++
- Position of rightmost different bit in C++
- k-th prime factor of a given number in java
- For every set bit of a number toggle bits of other in C++
- Golang Program to find the position of the rightmost set bit
