Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Sum Up a Number Until It Becomes 1 Digit in JavaScript



We are required to write a JavaScript function that takes in a Number as the only input. The function should do one simple thing −

  • keep adding the resultant digits until they converse to a single digit number.

For example −

const num = 5798;

i.e.

5 + 7 + 9 + 8 = 29
2 + 9 = 11
1 + 1 = 2

Hence, the output should be 2

Example

The code for this will be −

const num = 5798;
const sumDigits = (num, sum = 0) => {
   if(num){
      return sumDigits(Math.floor(num / 10), sum + (num % 10));
   };
   return sum;
};
const repeatSum = (num) => {
   if(num > 9){
      return repeatSum(sumDigits(num));
   };
   return num;
};
console.log(repeatSum(num));

Output

And the output in the console will be −

2
Updated on: 2020-11-25T12:03:49+05:30

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements