Problem Description: Take an integer n (n >= 0) and a digit d (0 <= d <= 9) as an integer. Square all numbers k (0 <= k <= n) between 0 and n. Count the numbers of digits d used in the writing of all the k**2. Call nb_dig (or nbDig or ...) the function taking n and d as parameters and returning this count.
Examples:
n = 10, d = 1, the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
We are using the digit 1 in 1, 16, 81, 100. The total count is then 4.
nb_dig(25, 1):
1, 4, 9, 10, 11, 12, 13, 14, 19, 21 squared are 1, 16, 81, 100, 121, 144, 169, 196, 361, 441
so there are 11 digits `1` for the squares of numbers between 0 and 25.
Note that 121 has twice the digit 1.
Level:7kyu
Link to Kata: Count the digit
My approach while solving this Kata was to go through string method rather than integer method. I first of all converted the integer which we have to count i.e. "d" to a string and assigned the string value to a new variable "str_d". We assign a variable count to a value of 0.
Then we start a loop where we go from the given input "n" to 0. In each step we assign the value of square of "n" in string format to a variable num. Then we find the count of "str_d" in num by using split method of Javascript and assign it to a variable matchCount. We add the value of matchCount to count and decrease the value of n by 1 in each looping step.
In the end we return the value of count as our answer.
Here is a link to the code: Kata Day 29
Please mention your suggestions or your doubts in the comment below.
Happy coding. :)
No comments:
Post a Comment