Skip to content

Sum up all digits of a number until it becomes one digit

Learn how to sum up all digits of a number until it becomes one digit in JavaScript.

Advertisements
const num = 987654;
const sumAllDigits = (num, sum = 0) => {
   if(num){
      return sumAllDigits(Math.floor(num / 10), sum + (num % 10));
   };
   return sum;
};
const recursiveSum = (num) => {
   if(num > 9){
      return recursiveSum(sumAllDigits(num));
   };
   return num;
};
console.log(recursiveSum(num)); //3
See also  Insertion Sort - Part 2 - Hackerrank Challenge - Java Solution

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.