- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reduce sum of digits recursively down to a one-digit number JavaScript
We have to write a function that takes in a number and keeps adding its digit until the result is not a one-digit number, when we have a one-digit number, we return it.
The code for this is pretty straightforward, we write a recursive function that keeps adding digit until the number is greater than 9 or lesser than -9 (we will take care of sign separately so that we don’t have to write the logic twice)
Example
const sumRecursively = (n, isNegative = n < 0) => { n = Math.abs(n); if(n > 9){ return sumRecursively(parseInt(String(n).split("").reduce((acc,val) => { return acc + +val; }, 0)), isNegative); } return !isNegative ? n : n*-1; }; console.log(sumRecursively(88)); console.log(sumRecursively(18)); console.log(sumRecursively(-345)); console.log(sumRecursively(6565));
Output
The output in the console will be −
7 9 -3 4
- Related Articles
- Digit sum upto a number of digits of a number in JavaScript
- Recursively adding digits of a number in JavaScript
- Summing up all the digits of a number until the sum is one digit in JavaScript
- Program to find sum of digits until it is one digit number in Python
- C program to find sum of digits of a five digit number
- Sum up a number until it becomes one digit - JavaScript
- C++ program to find sum of digits of a number until sum becomes single digit
- Finding sum of digits of a number until sum becomes single digit in C++
- Prime digits sum of a number in JavaScript
- Recursive sum all the digits of a number JavaScript
- Negative number digit sum in JavaScript
- Product sum difference of digits of a number in JavaScript
- The sum of digits of a two-digit number is 8. If 36 is added to the number then the digits reversed. Find the number.
- Sum of the digits of a two digit number is 9. When we interchange the digits of the two digit number, the resultant number exceeds the original number by 27. Find the number.
- Maximum of sum and product of digits until number is reduced to a single digit in C++

Advertisements