![]() |
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 DigitsIn this approach, we define a recursive function that takes an integer N as input and returns the sum of its digits. The base case occurs when the number is less than 10, in that case, the function simply returns the number itself. Example: The below code sums the digits of a number using recursion in JavaScript.
Output 6 15 45 Using string manipulation with recursionIn 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.
Output 6 15 45 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |