Was it helpful?

Question

Sum up a number until it becomes one digit - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that recursively sums up the digits of a number until it reduces to a single digit number. Do it without converting the number to String or any other data type.

Example

Following is the code −

const num = 546767643;
const sumDigit = (num, sum = 0) => {
   if(num){
      return sumDigit(Math.floor(num / 10), sum + (num % 10));
   }
   return sum;
};
const sumRepeatedly = num => {
   while(num > 9){
      num = sumDigit(num);
   };
   return num;
};
console.log(sumRepeatedly(num));

Output

This will produce the following output in console −

3
raja
Published on 30-Sep-2020 17:55:57
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top