在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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短