Recursive sum all the digits of a number JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, 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

So, the output should be 6.

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

Example

// 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.

Output

So, the output for this code will be −

3
raja
Published on 19-Aug-2020 10:32:28
Advertisements