|
| 1 | +/*************************************************************************************** |
| 2 | +* * |
| 3 | +* CODERBYTE BEGINNER CHALLENGE * |
| 4 | +* * |
| 5 | +* Additive Persistence * |
| 6 | +* Using the JavaScript language, have the function AdditivePersistence(num) take the * |
| 7 | +* num parameter being passed which will always be a positive integer and return its * |
| 8 | +* additive persistence which is the number of times you must add the digits in num * |
| 9 | +* until you reach a single digit. For example: if num is 2718 then your program * |
| 10 | +* should return 2 because 2 + 7 + 1 + 8 = 18 and 1 + 8 = 9 and you stop at 9. * * |
| 11 | +* * |
| 12 | +* SOLUTION * |
| 13 | +* The challenge passes a string but it expects us to do Math on it so it needs to * |
| 14 | +* be converted to numbers. I will use the base 10 parameter of the toString() * |
| 15 | +* function and the map() function to convert each entry in the array to a Number. * |
| 16 | +* Then I am going to sum each entry in the array to get a total. I will repeat this * |
| 17 | +* until my total is a single digit number. The number of times I sum is returned * |
| 18 | +* as the answer. * |
| 19 | +* * |
| 20 | +* Steps for solution * |
| 21 | +* 1) Initialize vars sum and loop * |
| 22 | +* 2) Convert str to an array of numbers * |
| 23 | +* 3) Loop until the sum of digits in array is a single digit number * |
| 24 | +* 4) Return number of loops as answer * |
| 25 | +* * |
| 26 | +***************************************************************************************/ |
| 27 | + |
| 28 | +function AdditivePersistence(num) { |
| 29 | + |
| 30 | + var sum, loop = 0; |
| 31 | + var val1 = num.toString(10).split("").map(function(t){return parseInt(t)}); |
| 32 | + |
| 33 | + while (val1.length > 1) { |
| 34 | + sum = 0; |
| 35 | + val1.forEach( function(number) { |
| 36 | + sum = sum + number; |
| 37 | + }); |
| 38 | + |
| 39 | + val1 = sum.toString(10).split("").map(function(t){return parseInt(t)}); |
| 40 | + loop++; |
| 41 | + } |
| 42 | + |
| 43 | + return loop; |
| 44 | + |
| 45 | +} |
0 commit comments