मान लीजिए हमारे पास एक बाइनरी स्ट्रिंग 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