假设我们有一个二进制字符串bin。然后对其应用n次迭代,在第n次迭代后,字符串中的第i个索引字符之后,在每次迭代中0变为01,1变为10。因此,如果二进制字符串是101,并且n = 2,i = 3,那么在第一次迭代后它将是100110,在下一次迭代中它将是100101101001,因此第一个索引保持为1。
为了解决这个问题,我们必须遵循以下步骤-
运行n次循环,并在每次迭代中对字符串运行另一个循环
转换二进制字符串的每个字符,如果为0,则存储01;如果为1,则将10存储为另一个临时字符串
内部循环完成后,将临时字符串存储为二进制字符串。
然后返回第一个索引。
#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);
}
输出结果
3rd character is: 1
9th character is: 0