Sequential Digits in C++


Suppose we have an integer, that has sequential digits if and only if each digit in the number is one more than the previous digit. We have to find a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. So if the low = 100 and high = 300, then the output will be [123,234]

To solve this, we will follow these steps −

  • create one array res
  • for i in range 1 to n
    • for j := 1, until j + i – 1 <= 9
      • x := 0
      • for k in range 0 to i – 1
        • x := 10x + (j + k)
      • if low < x and x <= high, then insert x into ans
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#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));
}

Input

500
5000

Output

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

Updated on: 02-May-2020

278 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements