在 n 次迭代之後,在 C++ 程式設計中,在一個二進位制字串中找到第 i 個索引字元


假設我們有一個二進位制字串 bin。然後對它執行 n 次迭代,並在每次迭代過程中 0 變成 01,1 變成 10。之後,字串中第 i 個索引字元在第 n 次迭代之後。因此,如果二進位制字串為 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

更新於: 18-12-2019

180 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.