在 C++ 中找到 n 次迭代後得到的二進位制字串中的第 i 個索引字元


假設我們有一個二進位制字串 bin。然後對其進行 n 次迭代,在每次迭代中 0 變為 01,1 變為 10,然後是第 n 次迭代後字串中的第 i 個索引字元。因此,如果二進位制字串為 101,並且 n = 2,i = 3,那麼在第一次迭代後它將變為 100110,在下次迭代中,它將變為 100101101001,因此第 i 個索引為 1。

為解決此問題,我們必須遵循以下步驟:

  • 迴圈執行 n 次,在每次迭代中再迴圈執行一次字串
    • 轉換二進位制字串的每個字元,如果為 0,則在另一個臨時字串中儲存 01 或如果為 1,則儲存 10
    • 在完成內部迴圈後,將臨時字串儲存到二進位制字串。
  • 然後返回第 i 個索引。

示例

 現場演示

#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

更新於:2019-12-17

178 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.