
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Recursive sum all the digits of a number JavaScript
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
- Related Questions & Answers
- Recursive product of all digits of a number - JavaScript
- Destructively Sum all the digits of a number in JavaScript
- Recursive sum of digits of a number formed by repeated appends in C++
- Recursive sum of digits of a number is prime or no in C++
- Prime digits sum of a number in JavaScript
- Recursive product of summed digits JavaScript
- Sorting digits of all the number of array - JavaScript
- Summing up all the digits of a number until the sum is one digit in JavaScript
- Digit sum upto a number of digits of a number in JavaScript
- Check if a number is magic (Recursive sum of digits is 1) in C++
- Product sum difference of digits of a number in JavaScript
- Program to find the sum of all digits of given number in Python
- Repeated sum of Number’s digits in JavaScript
- Checking whether the sum of digits of a number forms a Palindrome Number or not in JavaScript
- Sum a negative number (negative and positive digits) - JavaScript
Advertisements