Print all numbers from a given range that are made up of consecutive digits
Given a range [L, R], the task is to find all the numbers from the range [L, R] whose digits are consecutive. Print all those numbers in increasing order.
Input: L = 12, R = 34
Output: 12 23 34
Input: L = 12, R = 25
Output: 12 23
Approach: The given problem can be solved by generating all possible numbers and store all those numbers that satisfy the given condition. After generating all the numbers print all the stored numbers in sorted order. Follow the steps below to solve the given problem:
- Initialize a variable, say num as “” that stores the string form of all possible numbers having consecutive digits and in increasing order.
- Iterate over the range [1, 9] using the variable i and perform the following steps:
- Update the string num to the string form of i and if this value lies over the range [L, R], then store this in the vector Ans.
- Iterate over the range [1, 9] using the variable j add the character form of j to the string num, and if the integer form of the string num lies over the range [L, R], then store this in the vector Ans.
- After completing the above steps, sort the vector Ans to print all the numbers generated.
Below is the implementation of the above approach:
12 23 34 45 56 67 78
Time Complexity: O(1)
Space Complexity: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.