Computer >> Computer tutorials >  >> Programming >> C++

Find k-th bit in a binary string created by repeated invert and append operations 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 −

IterationValue (Initially 0)
101
20110
301101001
40110100110010110

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