Problem Description: In this kata, you must create a digital root function.
A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.
Here's how it works:
digital_root(16)
=> 1 + 6
=> 7
digital_root(942)
=> 9 + 4 + 2
=> 15 ...
=> 1 + 5
=> 6
Level: 6kyu
Link to Kata: Digital Root
To find a digital sum/root of a number, we have to find the sum of its digit and if that sum is a single digit number then it is our required digital root otherwise we again find the sum of digits of the digits of the sum acquired and keep on doing this until we get a single digit number.
In this Kata we enter a loop which is always true and inside it we convert the given number to a string and then loop through the string. We initialize a variable sum to 0 and while looping through the array we keep on adding every single digit of given number by parsing the character element of string to an integer. Once we get the sum we check if the length of sum when converted to a string is 1. If it is then we push the value of sum to n and break from the while loop. If it is not then we push the value of sum to n and continue with the previous process until we get a sum with a single digit.
In the output we return the value of n as our value of digital root.
Here is a link to the code: Kata Day 11
Please mention your suggestions or your doubts in the comment below.
Happy coding. :)
No comments:
Post a Comment