- 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
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
#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
- Related Articles
- Find i’th Index character in a binary string obtained after n iterations in C++ programming
- Find last index of a character in a string in C++
- C# program to replace n-th character from a given index in a string
- Program to find the kth character after decrypting a string in C++
- Find the n-th binary string in sorted order in C++
- Find the index of the first unique character in a given string using C++
- C++ program to find string after adding character 'a' string becomes non-palindrome
- Search index of a character in a string in Java
- Program to find maximum binary string after change in python
- Return index of first repeating character in a string - JavaScript
- Find one extra character in a string using C++.
- C# program to remove n-th character from a string
- Find the character in first string that is present at minimum index in second string in Python
- Find repeated character present first in a string in C++
- Binary String With Substrings Representing 1 To N in C++

Advertisements