Cho chuỗi nhị phân, mỗi lần lặp: 0→01, 1→10. Sau n lần lặp, tìm ký tự tại chỉ số i. Ví dụ "101", n=2, i=3 → sau lặp 1: 100110, lặp 2: 100101101001, ký tự 3 là 1.
Mô phỏng n lần: mỗi lần xây chuỗi mới từ chuỗi cũ bằng quy tắc chuyển đổi.
Ví dụ
#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); }
Kết quả
3rd character is: 1 9th character is: 0