If you want to calculate the number of increasing numbers, you can build a 2D table, where the rows correspond to the involved numbers and the columns to the number of digits. And you insert the number of increasing numbers with i
digits, using digits up to j
in the cells. The first column is easy:
1 digit 2 digits 3 digits ...
>= 0 10
>= 1 9
>= 2 8
>= 3 7
>= 4 6
>= 5 5
>= 6 4
>= 7 3
>= 8 2
>= 9 1
If you want to calculate the next column, you can refer to the previous one. Suppose you want to calculate cell(2, 9)
(two-digit numbers with digits greater than 9). Then you can put a 9 on front and use any 1-digit number with digits greater than 9. So, just 1. The same goes for cell(2, 8)
. You can put an 8 at front plus any 1-digit number with digits greater than 8 (cell(1, 8)
) plus the same numbers you used for the below cell. In general:
cell(i, j) = cell(i - 1, j) + cell(i, j + 1)
The first few columns are:
1 digit 2 digits 3 digits ...
>= 0 10 10+45=55 55+165=220
>= 1 9 9+36=45 45+120=165
>= 2 8 8+28=36 36+84=120
>= 3 7 7+21=28 28+56=84
>= 4 6 6+15=21 21+35=56
>= 5 5 5+10=15 15+20=35
>= 6 4 4+ 6=10 10+10=20
>= 7 3 3+ 2=6 6+ 4=10
>= 8 2 2+ 1=3 3+ 1=4
>= 9 1 1 1
The total number is always the entry cell(digits, 0)
. So there are 220 increasing numbers with three or less digits.
A similar table can be calculated for decreasing numbers. However, in order to calculate the number of decreasing numbers, you have to sum all columns. E.g. for three-digit decreasing numbers: 10+55+220=285
.
In order to calculate the increasing or decreasing numbers, just sum the two values and subtract numbers that are both increasing and decreasing. For every digit, it there will be 10. So for 3-digit numbers, you have to calculate 220+285-30=475
.
So, calculate the table iteratively. You just need to keep the current column and calculate the total number accordingly.