- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Advertisements