There are 10C2=45
ways to assign pairs (x,y)
— note that order is not important here, because x
,y
together represent the 2 digits allowed in the number. Take special care when either one is 0.
If neither are 0, there are 2^k
lucky numbers that are k digits containing those numbers. If x is 0, then it's 2^(k-1)
. But this double counts the numbers if x=y
.
a=10^k (ie. k 9's): # =9x2^(k-1)-9+36x2^k-36 -9k =81x2^(k-1)-45-9k (*)
We subtract 9k
because that is precisely the number of lucky numbers containing only 1 digit
Thereafter, the only necessary consideration left is the last segment of lucky numbers from a to n, all of which are k digits long.
For example, in the given test case, n=123, ans=113.
a=100=10^2=02 x 9's (as in '99') => k=3
By (*), k=2: #=99
; k=3: #=252
There are 99 lucky numbers between 1 and 99 inclusive.
Between a=100 <= n=123
, there are 3+9+2=14
more lucky numbers, specifically as follows:
- 100,101,110
- 111 — 119
- 121, 122