简体   繁体   中英

Frequency of occurrence of a digit?

I have tried to solve this algorithm in JavaScrip and I couldn't make it. I have done it in Java but I can't find a way to solve this is JS. If somebody can show me and explain to me the solution I would be grateful to the moon and back :) The algorithm:

Find the frequency of occurrence of a given digit in all whole numbers between 0 and a given positive integer (both inclusive).

Let's say that the number to count (we'll call it K) is 2.

So, between 0 and 35, the K (in this case 2) appears 14 times:

2, 12, 20, 21, 22 (twice), 23, 24, 25, 26, 27, 28, 29 32 = 14 times

Input

Input consists of 2 lines. First line contains the number (K) which the program needs to count. Second line contains the number N, which is the maximum number in the range to check for occurrences of K (for example, between 0 and N). All number are positive whole numbers. There are no decimals or fractions.

Output

Print the number of K's appearing between 0 and N (both inclusive). Print 0 if not found.

Thank you in advance.

Possible solution, might be more efficient onces.

let k = String(2);
let n = 35;
let s = String("");

// create string from numbers 0 to n
for (let i = 0; i <= n; i++) s += i;

// check each character for digit
let occurs = s.split('').reduce((a, x) => x === k ? a + 1 : a, 0);

// print result
console.log(occurs);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM