
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find K-th Bit in a Binary String in C++
Suppose we have a binary string s, initially this is say “0”. Now in each iteration invert it, and append it, thus after nth iteration, we will find the kth bit. Suppose the number of iteration is 4, and k = 7, so it will be −
Iteration | Value (Initially 0) |
---|---|
1 | 01 |
2 | 0110 |
3 | 01101001 |
4 | 0110100110010110 |
so 7th bit is 1.
In each iteration, find complement, and append, thus after nth iteration, finds kth bit
Example
#include<iostream> using namespace std; string getComplement(string bin){ string temp = ""; for(int i= 0; i<bin.length(); i++){ if(bin[i] == '0') temp += "1"; else temp += "0"; } return temp; } char getCharacter(string bin_str, int n, int k) { string res = bin_str; for(int i = 0; i<n; i++){ res += getComplement(res); } return res[k]; } int main() { int n = 4; string bin = "0"; cout << 7 << "th character is: "<< getCharacter(bin, n, 7); }
Output
7th character is: 1
Advertisements