CoineTre

Persistent Bugger - kata

Oct 9th, 2024
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 0.96 KB | Source Code | 0 0
  1. function persistence(num) {
  2.    let digits = num.toString();
  3.   if (digits.length === 1) {
  4.     return 0;
  5.   }
  6.   let calculate =1;
  7.   let counter = 0;
  8.   while (digits.length > 1) {
  9.     for (let i = 0; i < digits.length; i++) {
  10.         calculate *= digits[i];
  11.         }
  12.         digits = String(calculate);
  13.         calculate = 1;
  14.     counter++;
  15.     }
  16.    
  17.  
  18.   return counter;
  19. }
  20.  
  21. console.log(persistence(39));
  22.  
  23. /* Description:
  24.  
  25. 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.
  26.  
  27. For example (Input --> Output):
  28.  
  29. 39 --> 3 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit, there are 3 multiplications)
  30. 999 --> 4 (because 9*9*9 = 729, 7*2*9 = 126, 1*2*6 = 12, and finally 1*2 = 2, there are 4 multiplications)
  31. 4 --> 0 (because 4 is already a one-digit number, there is no multiplication)
  32. */
Add Comment
Please, Sign In to add comment