在C++中查詢包含數字d的數字


考慮一個數字d和上限n。我們必須在0到n的範圍內找到包含d的所有數字。因此,如果n = 20且數字為3,則數字將為[3, 13]。

為了解決這個問題,我們將把每個數字作為字串,然後如果字串中存在該數字,則將列印該數字,否則將忽略它。

示例

#include<iostream>
using namespace std;
int getAllNumWithDigit(int n, int d) {
   string str = "";
   str += to_string(d);
   char ch = str[0];
   string p = "";
   p += ch;
   for (int i = 0; i <= n; i++) {
      str = "";
      str = str + to_string(i);
      int index = str.find(p);
      if (i == d || index!=-1)
         cout << (i) << " ";
   }
}
int main() {
   int n = 100; int d = 3;
   getAllNumWithDigit(n, d);
}

輸出

3 13 23 30 31 32 33 34 35 36 37 38 39 43 53 63 73 83 93

更新日期: 2019年11月4日

102次觀看

開啟你的 職業

完成課程認證

開始
廣告