Skip to content

Instantly share code, notes, and snippets.

@wicksome
Last active November 14, 2019 08:14
Show Gist options
  • Save wicksome/3823b5c3d575eb846c12a4b5e5810175 to your computer and use it in GitHub Desktop.
Save wicksome/3823b5c3d575eb846c12a4b5e5810175 to your computer and use it in GitHub Desktop.
get total count of specific digit(0~9) from 1 to number

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)
})
}
@wicksome
Copy link
Author

wicksome commented Nov 14, 2019

 // 0 ~ 9
Math.floor(num % 10) >= digit ? 1 : 0 // units
// 0 ~ 99
(Math.floor(num / 10) + (Math.floor(num / 10) > digit ? 10 : 0)) // tens
+ (Math.floor(num % 10) >= digit ? 1 : 0); // units
// hundreds(100)
// thousands(1000)
// ten thousands(10000)
// hundred thousands(100000)
// millions(1000000)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment