Summing up all the digits of a number until the sum is one digit in JavaScript

JavascriptWeb DevelopmentObject Oriented ProgrammingFront End Technology

We are required to create a function that takes in a number and finds the sum of its digits recursively until the sum is a one-digit number.

For example

findSum(12345) = 1+2+3+4+5 = 15 = 1+5 = 6

Therefore, the output should be 6.

Let’s write the code for this function findSum()

// using recursion
const findSum = (num) => {
   if(num < 10){
      return num;
   }
   const lastDigit = num % 10;
   const remainingNum = Math.floor(num / 10);
   return findSum(lastDigit + findSum(remainingNum));
}
console.log(findSum(2568));

We check if the number is less than 10, it’s already minified and we should return it and from the function otherwise we should return the call to the function that recursively takes the last digit from the number adds to it until it becomes less than 10.

Therefore, the output for this code will be −

3
raja
Published on 10-Oct-2020 07:25:32
Advertisements