Print all n-digit strictly increasing numbers in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a number N and we have to print all n-digit numbers whose digits are strickly increasing from MSB to LSB i.e. the number at LSB (left) should be smaller than the number at right.

Let’s take an example to understand the problem −

Input − n = 2

Output 

01 02 03 04 05 06 07 08 09 12 13 14 15 16 17 18 19 23 24 25 26 27 28 
29 34 35 36 37 38 39 45 46 47 48 49 56 57 58 59 67 68 69 78 79 89.

Explanation − as you can see all the numbers at the left are smaller than the numbers at the right of them.

To solve this problem, we will start from the MSB (left side) with numbers one by one and then generate numbers according to the condition. The next position will contain digits from i+1 to 9, i is the digit at the current position.

The code to implement code logic −

Example

 Live Demo

#include <iostream>
using namespace std;
void printIncresingNumbers(int start, string out, int n) {
   if (n == 0){
      cout<<out<<" ";
      return;
   }
   for (int i = start; i <= 9; i++){
      string str = out + to_string(i);
      printIncresingNumbers(i + 1, str, n - 1);
   }
}
int main() {
   int n = 3;
   cout<<"All "<<n<<" digit strictly increasing numbers are :\n";
   printIncresingNumbers(0, "", n);
   return 0;
}

Output

All 3 digit strictly increasing numbers are −
012 013 014 015 016 017 018 019 023 024 025 026 027 028 029 034 035 036 
037 038 039 045 046 047 048 049 056 057 058 059 067 068 069 078 079 089 
123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 
156 157 158 159 167 168 169 178 179 189 234 235 236 237 238 239 245 246 
247 248 249 256 257 258 259 267 268 269 278 279 289 345 346 347 348 349 
356 357 358 359 367 368 369 378 379 389 456 457 458 459 467 468 469 478 
479 489 567 568 569 578 579 589 678 679 689 789
raja
Published on 22-Jan-2020 15:04:32
Advertisements