How many times can we sum number digits in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an positive integer and returns its additive persistence.

The additive persistence of an integer, say n, is the number of times we have to replace the number with the sum of its digits until the number becomes a single digit integer.

For example: If the number is −

1679583

Then,

1 + 6 + 7 + 9 + 5 + 8 + 3 = 39 // 1 Pass
3 + 9 = 12 // 2 Pass
1 + 2 = 3 // 3 Pass

Therefore, the output should be 3.

Example

The code for this will be −

const num = 1679583;
const sumDigit = (num, sum = 0) => {
   if(num){
      return sumDigit(Math.floor(num / 10), sum + num % 10);
   };
   return sum;
};
const persistence = num => {
   num = Math.abs(num);
   let res = 0;
   while(num > 9){
      num = sumDigit(num);
      res++;
   };
   return res;
};
console.log(persistence(num));

Output

The output in the console will be −

3
raja
Published on 17-Oct-2020 11:47:33
Advertisements