## Algorithm

Problem Name: 902. Numbers At Most N Given Digit Set

Given an array of `digits` which is sorted in non-decreasing order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`.

Return the number of positive integers that can be generated that are less than or equal to a given integer `n`.

Example 1:

```Input: digits = ["1","3","5","7"], n = 100
Output: 20
Explanation:
The 20 numbers that can be written are:
1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.
```

Example 2:

```Input: digits = ["1","4","9"], n = 1000000000
Output: 29523
Explanation:
We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,
81 four digit numbers, 243 five digit numbers, 729 six digit numbers,
2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.
In total, this is 29523 integers that can be written using the digits array.
```

Example 3:

```Input: digits = ["7"], n = 8
Output: 1
```

Constraints:

• `1 <= digits.length <= 9`
• `digits[i].length == 1`
• `digits[i]` is a digit from `'1'` to `'9'`.
• All the values in `digits` are unique.
• `digits` is sorted in non-decreasing order.
• `1 <= n <= 109`

## Code Examples

### #1 Code Example with Javascript Programming

```Code - Javascript Programming```

``````
const atMostNGivenDigitSet = function(digits, n) {
const str = '' + n, { pow } = Math
const len = str.length, dsize = digits.length
let res = 0

for(let i = 1; i < len; i++) {
res += pow(dsize, i)
}

for(let i = 0; i < len; i++) {
for(const d of digits) {
if(+d < +str[i]) {
res += pow(dsize, len - i - 1)
} else if(+d === +str[i]) sameNum = true
}
}

return res + 1
};
``````
Copy The Code &

Input

cmd
digits = ["1","3","5","7"], n = 100

Output

cmd
20

### #2 Code Example with Python Programming

```Code - Python Programming```

``````
class Solution:
def atMostNGivenDigitSet(self, D, N):
def less(c):
return len([char for char in D if char < c])
d, cnt, l = len(D), 0, len(str(N))
# For numbers which have less digits than N, simply len(D) ** digits_length different numbers can be created
for i in range(1, l):
cnt += d ** i
"""
We should also consider edge cases where previous digits match with related digits in N. In this case, we can make a number with             previous digits + (digits less than N[i]) + D ** remaining length
"""
for i, c in enumerate(str(N)):
cnt += less(c) * (d ** (l - i - 1))
if c not in D: break
if i == l - 1: cnt += 1
return cnt
``````
Copy The Code &

Input

cmd
digits = ["1","3","5","7"], n = 100

Output

cmd
20