Skip to content

Commit eba8608

Browse files
authored
Update 1012-numbers-with-repeated-digits.js
1 parent 6965e20 commit eba8608

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

1012-numbers-with-repeated-digits.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,67 @@
1+
/**
2+
* @param {number} n
3+
* @return {number}
4+
*/
5+
function numDupDigitsAtMostN(n) {
6+
let numNoDupDigits = 0; // the number of positive integers less than or equal to n with no repeated digits
7+
8+
let lst = Array.from(String(n), Number);
9+
let n_digits = lst.length;
10+
11+
// if n = 8765, lst = [8,7,6,5],
12+
// the number without repeated digit can the the following format:
13+
// XXX
14+
// XX
15+
// X
16+
for (let i = 1; i < n_digits; i++) {
17+
// the number of i digits without repeated digit
18+
// the leading digit cannot be 0
19+
numNoDupDigits += 9 * perm(9, i - 1);
20+
}
21+
22+
// and
23+
// 1XXX ~ 7XXX
24+
// 80XX ~ 86XX
25+
// 870X ~ 875X
26+
// 8760 ~ 8764
27+
let seen = new Set();
28+
for (let i = 0; i < lst.length; i++) {
29+
let x = lst[i];
30+
for (let y = (i === 0 ? 1 : 0); y < x; y++) {
31+
if (!seen.has(y)) {
32+
// the leading digit used - y
33+
// for the remaining positions we cannot use digits in set seen and y
34+
numNoDupDigits += perm(9 - i, n_digits - i - 1);
35+
}
36+
}
37+
if (seen.has(x)) {
38+
break;
39+
}
40+
seen.add(x);
41+
}
42+
43+
// and
44+
// 8765
45+
if (n_digits === new Set(lst).size) {
46+
numNoDupDigits += 1;
47+
}
48+
49+
return n - numNoDupDigits;
50+
}
51+
52+
function perm(m, n) {
53+
let res = 1
54+
for(let i = 0; i < n; i++) {
55+
res *= m
56+
m--
57+
}
58+
59+
return res
60+
}
61+
62+
// another
63+
64+
165
/**
266
* @param {number} n
367
* @return {number}

0 commit comments

Comments
 (0)