Find i’th index character in a binary string obtained after n iterations in C++


Suppose we have a binary string bin. Then apply n iterations on it, and in each iteration 0 becomes 01 and 1 becomes 10, after that ith index character in the string after nth iteration. So if the binary string is 101, and n = 2, and i = 3, so after first iteration it will be 100110, in the next iteration, it will be 100101101001, so ith index is holding 1.

To solve this, we have to follow these steps −

  • Run loop n times, and in each iteration run another loop on the string
    • Convert each character of binary string, and if that is 0, then store 01 or if that is 1, then store 10 into another temporary string
    • After completion of inner loop, store temporary string to binary string.
  • Then return ith index.

Example

 Live Demo

#include<iostream>
using namespace std;
char getCharacter(string bin_str, int n, int i) {
   string temp = "";
   for (int x = 0; x < n; x++) {
      for (int y = 0; y < bin_str.length(); y++) {
         if (bin_str[y] == '1')
            temp += "10";
         else
            temp += "01";
      }
      bin_str = temp;
      temp = "";
   }
   return bin_str[i];
}
int main() {
   int n = 2;
   string bin = "101";
   cout << 3 << "rd character is: "<< getCharacter(bin, n, 3)<<endl;
   cout << 9 << "th character is: "<< getCharacter(bin, n, 9);
}

Output

3rd character is: 1
9th character is: 0

Updated on: 17-Dec-2019

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements