-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy path1067-digit-count-in-range.js
80 lines (74 loc) · 1.75 KB
/
1067-digit-count-in-range.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* @param {number} d
* @param {number} low
* @param {number} high
* @return {number}
*/
const digitsCount = function(d, low, high) {
return countDigit(high, d) - countDigit(low - 1, d)
};
function countDigit(limit, d) {
let res = 0
const str = `${limit}`
const len = str.length
const { pow } = Math
if(d === 0) {
for(let i = 1; i < len; i++) {
const pre = ~~(limit / pow(10, i))
const post = pow(10, i - 1)
res += (pre - 1) * post
const e = +str[len - i]
if(e > d) {
res += post
} else if(e === d) {
res += (limit % post) + 1
}
}
} else {
for(let i = 1; i <= len; i++) {
const pre = ~~(limit / pow(10, i))
const post = pow(10, i - 1)
res += pre * post
const e = +str[len - i]
if(e > d) {
res += post
} else if(e === d) {
res += (limit % post) + 1
}
}
}
return res
}
// another
/**
* @param {number} d
* @param {number} low
* @param {number} high
* @return {number}
*/
const digitsCount = function (d, low, high) {
return countDigit(high, d) - countDigit(low - 1, d)
function countDigit(n, d) {
if (n < 0 || n < d) {
return 0
}
let count = 0
for (let i = 1; i <= n; i *= 10) {
let divider = i * 10
count += ((n / divider) >> 0) * i
if (d > 0) {
// tailing number need to be large than d * i to qualify.
count += Math.min(Math.max((n % divider) - d * i + 1, 0), i)
} else {
if (n / divider > 0) {
if (i > 1) {
// when d == 0, we need avoid to take numbers like 0xxxx into account.
count -= i
count += Math.min((n % divider) + 1, i)
}
}
}
}
return count
}
}