
- 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
How many times can we 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
- Related Questions & Answers
- Count how many times the given digital clock shows identical digits in C++
- In how many ways can we split a string in JavaScript?
- Prime digits sum of a number in JavaScript
- Repeated sum of Number’s digits in JavaScript
- Program to find how many ways we can climb stairs (maximum steps at most k times) in Python
- Program to count how many times we can find "pizza" with given string characters in Python
- Recursive sum all the digits of a number JavaScript
- Sum a negative number (negative and positive digits) - JavaScript
- Find the most frequent number in the array and how many times it is repeated in JavaScript
- Destructively Sum all the digits of a number in JavaScript
- Product sum difference of digits of a number in JavaScript
- Digit sum upto a number of digits of a number in JavaScript
- In how many ways can we find a substring inside a string in javascript?
- In how many ways we can concatenate Strings in Java?
- Counting how many times an item appears in a multidimensional array in JavaScript
Advertisements