Skip to content

Commit 845a84a

Browse files
authored
Update 233-number-of-digit-one.js
1 parent c941078 commit 845a84a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

233-number-of-digit-one.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,29 @@
1+
/**
2+
* @param {number} n
3+
* @return {number}
4+
*/
5+
const countDigitOne = function(n) {
6+
return countNum(1, n + 1)
7+
};
8+
9+
// Counts the number of `digit` in the range [0, limit)
10+
function countNum( digit, limit) {
11+
let count = 0;
12+
let factor = 1;
13+
let tail = 0;
14+
while (limit >= 10) {
15+
let d = limit % 10;
16+
limit = ~~(limit / 10);
17+
count += limit * factor;
18+
count += d > digit ? factor : d == digit ? tail : 0;
19+
tail += d * factor;
20+
factor *= 10;
21+
}
22+
return count + (limit > digit ? factor : limit == digit ? tail : 0);
23+
}
24+
25+
// another
26+
127
/**
228
* @param {number} n
329
* @return {number}

0 commit comments

Comments
 (0)