C++ 中的連續數字


假設我們有一個整數,它僅在數中的每個數字都比前一個數字大一時才具有連續的數字。我們必須找到範圍內所有具有連續數字整數的有序列表,包括 [low, high]。因此,如果 low = 100,high = 300,則輸出將是 [123,234]

為解決此問題,我們將按照以下步驟執行操作 −

  • 建立一個數組 res
  • 對於 i 中的範圍為 1 到 n
    • 對於 j := 1,直到 j + i – 1 <= 9
      • x := 0
      • 對於 range 中的 0 到 i – 1 的 k
        • x := 10x + (j + k)
      • 如果 low < x 且 x <= high,則將 x 插入到 ans 中
  • 返回 ans

我們來看看以下實現以獲得更好的理解 −

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector<int> sequentialDigits(int low, int high) {
      vector <int> ans;
      for(int i = 1; i <= 9; i++){
         for(int j = 1; j + i - 1 <= 9; j++){
            int x = 0;
            for(int k = 0; k < i; k++){
               x = (x*10) + (j + k);
            }
            if(low <= x && x <= high){
               ans.push_back(x);
            }
         }
      }
      return ans;
   }
};
main(){
   Solution ob;
   print_vector(ob.sequentialDigits(500, 5000));
}

輸入

500
5000

輸出

[567, 678, 789, 1234, 2345, 3456, 4567, ]

更新於: 02-05-2020

365 次瀏覽

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.