Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Finding persistence of number 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
Following is the code −
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
Following is the output in the console −
3
Advertisements
