-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindrome chain length
32 lines (22 loc) · 1.21 KB
/
Palindrome chain length
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
7 kyu
Palindrome chain length
Number is a palindrome if it is equal to the number with digits in reversed order. For example, 5, 44, 171, 4884 are palindromes, and 43, 194, 4773 are not.
Write a function which takes a positive integer and returns the number of special steps needed to obtain a palindrome. The special step is: "reverse the digits, and add to the original number". If the resulting number is not a palindrome, repeat the procedure with the sum until the resulting number is a palindrome.
If the input number is already a palindrome, the number of steps is 0.
All inputs are guaranteed to have a final palindrome which does not overflow MAX_SAFE_INTEGER.
Example
For example, start with 87:
87 + 78 = 165 - step 1, not a palindrome
165 + 561 = 726 - step 2, not a palindrome
726 + 627 = 1353 - step 3, not a palindrome
1353 + 3531 = 4884 - step 4, palindrome!
const palindromeChainLength = function(n) {
const reversed = parseInt((""+n).split('').reverse().join(''))
if(n != reversed){
return 1 + palindromeChainLength (n + reversed)
}
return 0;
};
console.log(palindromeChainLength(87), 4);
console.log(palindromeChainLength(89), 24);
console.log(palindromeChainLength(10), 1);