How can you help?
You can support by buying a coffee ☕️
Follow me on Github
Follow me on Twitter
Instructions
Task:
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
Example
39 --> 3 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit)
999 --> 4 (because 9*9*9 = 729, 7*2*9 = 126, 1*2*6 = 12, and finally 1*2 = 2)
4 --> 0 (because 4 is already a one-digit number)
My solution:
function persistence(num) {
let count = 0;
while(num.toString().length > 1){
num = num.toString().split('').reduce((acc,el)=>acc *= +el,1)
count++
}
return count
}
Explanation
First I created the variable count, where I'll save the number of times the number had to be multiplied so it gets to only one digit
let count = 0;
Then I used a while loop that will iterate until the length of the number is 1
while(num.toString().length > 1)
Inside of that while loop, I revalued the variable "num" to save the result of the multiplication of the digits, I did this by splitting the number into an array, and then I just used the reduce function to save the result of the multiplication of the digits.
Note: In the next iteration of the loop the variable "num" will be the result of the multiplication from the last digits
After that I just added one to the count variable
num = num.toString().split('').reduce((acc,el)=>acc *= +el,1)
count++
At the end I just returned count
return count
What do you think about this solution? 👇🤔
Top comments (0)