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 → lần 1: "100110", lần 2: "100101101001" → ký tự 3 là '1'.
Mô phỏng: lặp n lần, mỗi lần xây chuỗi mới từ chuỗi cũ. Trả về ký tự tại 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 << "3rd character is: " << getCharacter(bin, n, 3) << endl;
cout << "9th character is: " << getCharacter(bin, n, 9);
}
Kết quả
3rd character is: 1 9th character is: 0