How to use string manipulation with recursion In Javascript
In this approach, we convert the number to a string usin toString() method, split it into individual digits using split() method, and then recursively sum them up.
Example: The below code sums up the digits of a number using string manipulation in JavaScript.
function sumOfDigits(number) {
let digits =
number.toString().split('').
map(Number);
if (digits.length === 1) {
return digits[0];
} else {
let newNum = Number(digits.slice(1).join(''));
return digits[0] + sumOfDigits(newNum);
}
}
console.log(sumOfDigits(123));
console.log(sumOfDigits(249));
console.log(sumOfDigits(123456789));
Output
6 15 45
JavaScript Program for Sum of Digits of a Number using Recursion
We are given a number as input and we have to find the sum of all the digits contained by it. We will split the digits of the number and add them together using recursion in JavaScript.
Table of Content
- Recursively Summing Digits
- Using string manipulation with recursion
Contact Us