get total count of specific digit(0~9) from 1 to number
https://www.acmicpc.net/problem/14912
Example
> getDigitTotal(10, 1)
> 2
// 1 = 1
// 2 = 0
// ...
// 10 = 1
> getDigitTotal(11, 1)
> 4
// 1 = 1
// 2 = 0
// ...
// 10 = 1
// 11 = 2
get total count of specific digit(0~9) from 1 to number
https://www.acmicpc.net/problem/14912
Example
> getDigitTotal(10, 1)
> 2
// 1 = 1
// 2 = 0
// ...
// 10 = 1
> getDigitTotal(11, 1)
> 4
// 1 = 1
// 2 = 0
// ...
// 10 = 1
// 11 = 2
function getDigitTotal(num, digit) { | |
const regex = new RegExp(`${digit}`, "g"); | |
let sum = 0; | |
for (i = 1; i <= num; i++) { | |
const count = (`${i}`.match(regex)||[]).length; | |
sum += count; | |
} | |
return sum; | |
} |
function tc() { | |
[ | |
{ num: 1, digit: 1, result: 1 }, | |
{ num: 2, digit: 1, result: 1 }, | |
{ num: 3, digit: 1, result: 1 }, | |
{ num: 4, digit: 1, result: 1 }, | |
{ num: 5, digit: 1, result: 1 }, | |
{ num: 9, digit: 1, result: 1 }, | |
{ num: 10, digit: 1, result: 2 }, | |
{ num: 20, digit: 1, result: 12 }, | |
{ num: 22, digit: 1, result: 13 }, | |
{ num: 22, digit: 2, result: 6 }, | |
{ num: 70, digit: 1, result: 17 }, | |
{ num: 70, digit: 6, result: 17 }, | |
{ num: 70, digit: 7, result: 8 }, | |
{ num: 1000, digit: 1, result: 301 }, | |
{ num: 2000, digit: 1, result: 1600 }, | |
].forEach(({num, digit, result}) => { | |
const actual = getDigitTotal(num, digit); | |
const isSuccess = actual === result; | |
const logMessage = `expect: ${result}, actual: ${actual} (num: ${num}, digit: ${digit})` | |
isSuccess ? console.log(logMessage) : console.error(logMessage) | |
}) | |
} |