
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Sum Number Digits in JavaScript
We are required to write a JavaScript function that takes in an positive integer and returns its additive persistence.
The additive persistence of an integer, say n, is the number of times we have to replace the number with the sum of its digits until the number becomes a single digit integer.
For example: If the number is −
1679583
Then,
1 + 6 + 7 + 9 + 5 + 8 + 3 = 39 // 1 Pass 3 + 9 = 12 // 2 Pass 1 + 2 = 3 // 3 Pass
Therefore, the output should be 3.
Example
The code for this will be −
const num = 1679583; const sumDigit = (num, sum = 0) => { if(num){ return sumDigit(Math.floor(num / 10), sum + num % 10); }; return sum; }; const persistence = num => { num = Math.abs(num); let res = 0; while(num > 9){ num = sumDigit(num); res++; }; return res; }; console.log(persistence(num));
Output
The output in the console will be −
3
Advertisements