-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7-9-21.js
More file actions
44 lines (35 loc) · 1.88 KB
/
Copy path7-9-21.js
File metadata and controls
44 lines (35 loc) · 1.88 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
// 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!
// 4884 is a palindrome and we needed 4 steps to obtain it, so answer for 87 is 4.
// Additional info
// Some interesting information on the problem can be found in this Wikipedia article on Lychrel numbers.
var palindromeChainLength = function(n) {
let stepCount = 0
const checkPalindrome = num => num === Number(num.toString().split('').reverse().join(''))
if (checkPalindrome(n)) return stepCount
else {
while (!checkPalindrome(n)){
stepCount++
n += Number(n.toString().split('').reverse().join(''))
}
}
return stepCount
};
/*
declare a reverseN variable that is assigned n backwards
write a function to check if a number added to its reverseN will equal
a palindrome
the function should reverse the input number add it to the original
and then check for palindrome
run a while loop with a counter that will count the number of times
the function is run and also updates n to be the new sum
*/