Each week, I offer up a JavaScript code challenge. Want more? You can find others here.
First, I’ll admit that I’m a day overdue on this code challenge. Last week, I was on vacation in Austin, TX, and I’m still playing catchup. Still, that’s no excuse! After being away for a week, I felt a bit rusty. Today’s code challenge is a shorter one from Coderbyte.
Using the JavaScript language, have the function AdditivePersistence(num) take the num parameter being passed which will always be a positive integer and return its additive persistence which is the number of times you must add the digits in num until you reach a single digit. For example: if num is2718 then your program should return 2 because 2 + 7 + 1 + 8 = 18 and 1 + 8 = 9 and you stop at 9.
Here’s my solution collapsed:
[code language=”javascript” collapse=”true”]
function AdditivePersistence(num) {
// Break up the numbers into an array
var numbers = num.toString().split(”);
// Set the initial count to 0
var count = 0;
// Return the count if num is a single number
if (numbers.length <= 1) {
return count;
};
// If num isn’t a single number
do {
// Set the initial sum to 0
var sum = 0;
// Loop over the numbers array and add each number to the sum
for (var i = 0; i<numbers.length; i++) {
sum = sum + Number(numbers[i]);
}
// Set numbers equal to the new array after splitting the sum
numbers = sum.toString().split(”);
// Increment the count variable
count = count + 1;
// Do this while numbers.length is larger than 1
} while (numbers.length > 1);
return count;
};
[/code]
First, I took the num
argument passed in and split it up into an array so I could cycle over it. If the array had a length of 1, I could just return 0.
If the length of the array was larger than 1, I started a do/while loop. I cycled over each number in the array with a for loop and added it to the sum variable. At the end of the for loop, I set the numbers variable equal to the sum broken up into an array. For example, if the initial number was 2345, the sum would be 14. So, the numbers variable would be set equal to [1,4]
. I repeated this process while numbers.length
was greater than 1. Finally, I returned the count, which was incremented each time I went through the do/while loop.