이진 문자열 s가 있다고 가정합니다. 처음에는 "0"입니다. 이제 각 반복에서 이를 반전하고 추가합니다. 따라서 n번째 반복 후에 k번째 비트를 찾습니다. 반복 횟수가 4이고 k =7이라고 가정하면 -
| 반복 | 값(초기 0) |
|---|---|
| 1 | 01 |
| 2 | 0110 |
| 3 | 01101001 |
| 4 | 0110100110010110 |
그래서 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