在C ++中通过重复的反转和追加操作创建的二进制字符串中找到第k位
假设我们有一个二进制字符串s,起初是“0”。现在,在每次迭代中将其求逆,然后追加它,因此在第n次迭代后,我们将找到第k位。假设迭代次数为4,且k=7,则其为-
所以第7位是1。
在每次迭代中,找到补码,然后追加,因此在第n次迭代后,找到第k位
示例
#include<iostream>
using namespace std;
string getComplement(string bin){
string temp = "";
for(int i= 0; i<bin.length(); i++){
if(bin[i] == '0')
temp += "1";
else
temp += "0";
}
return temp;
}
char getCharacter(string bin_str, int n, int k) {
string res = bin_str;
for(int i = 0; i<n; i++){
res += getComplement(res);
}
return res[k];
}
int main() {
int n = 4;
string bin = "0";
cout << 7 << "th character is: "<< getCharacter(bin, n, 7);
}输出结果
7th character is: 1