Skip to content

Commit b84a846

Browse files
committed
Add solution #902
1 parent d3f1d89 commit b84a846

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,7 @@
712712
899|[Orderly Queue](./0899-orderly-queue.js)|Hard|
713713
900|[RLE Iterator](./0900-rle-iterator.js)|Medium|
714714
901|[Online Stock Span](./0901-online-stock-span.js)|Medium|
715+
902|[Numbers At Most N Given Digit Set](./0902-numbers-at-most-n-given-digit-set.js)|Hard|
715716
905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy|
716717
909|[Snakes and Ladders](./0909-snakes-and-ladders.js)|Medium|
717718
912|[Sort an Array](./0912-sort-an-array.js)|Medium|
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 902. Numbers At Most N Given Digit Set
3+
* https://leetcode.com/problems/numbers-at-most-n-given-digit-set/
4+
* Difficulty: Hard
5+
*
6+
* Given an array of digits which is sorted in non-decreasing order. You can write numbers using
7+
* each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write
8+
* numbers such as '13', '551', and '1351315'.
9+
*
10+
* Return the number of positive integers that can be generated that are less than or equal to
11+
* a given integer n.
12+
*/
13+
14+
/**
15+
* @param {string[]} digits
16+
* @param {number} n
17+
* @return {number}
18+
*/
19+
var atMostNGivenDigitSet = function(digits, n) {
20+
const str = n.toString();
21+
const digitCount = digits.length;
22+
let result = 0;
23+
24+
for (let i = 1; i < str.length; i++) {
25+
result += Math.pow(digitCount, i);
26+
}
27+
28+
function countValid(prefixLen) {
29+
if (prefixLen === str.length) return 1;
30+
31+
const currentDigit = str[prefixLen];
32+
let valid = 0;
33+
34+
for (const digit of digits) {
35+
if (digit < currentDigit) {
36+
valid += Math.pow(digitCount, str.length - prefixLen - 1);
37+
} else if (digit === currentDigit) {
38+
valid += countValid(prefixLen + 1);
39+
} else {
40+
break;
41+
}
42+
}
43+
44+
return valid;
45+
}
46+
47+
return result + countValid(0);
48+
};

0 commit comments

Comments
 (0)