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

 Live Demo

#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
Updated on: 2019-12-18T10:57:22+05:30

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements