在 C++ 中將長度為“k”的所有子串從基數“b”轉換為十進位制數


在本教程中,我們將討論將長度為“k”的所有子串從基數“b”轉換為十進位制數的程式。

為此,我們將獲得一定長度的字串。我們的任務是從給定的大小為“k”的字串中獲取子串,並將其從“b”基數轉換為十進位制數。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
//converting the substrings to decimals
int convert_substrings(string str, int k, int b){
   for (int i=0; i + k <= str.size(); i++){
      //getting the substring
      string sub = str.substr(i, k);
      //calculating the decimal equivalent
      int sum = 0, counter = 0;
      for (int i = sub.size() - 1; i >= 0; i--){
         sum = sum + ((sub.at(i) - '0') * pow(b, counter));
         counter++;
      }
      cout << sum << " ";
   }
}
int main(){
   string str = "12212";
   int b = 3, k = 3;
   convert_substrings(str, b, k);
   return 0;
}

輸出

17 25 23

更新於:16-Jan-2020

73 次瀏覽

開啟你的 事業

完成課程獲得認證

開始學習
廣告
© . All rights reserved.