Palindromes, math and recursion oh my!
I've been out of the blogging habit for a little bit, but I am now less than a week away from graduating from my bootcamp! Most of my time in the last few weeks has been devoted to networking and job applications but there are a few required sessions to attend. Last week, we had a mock react app take-home to build and present, and this week we have a new leetcode-style technical challenge to complete each day. I admit, these are not my strong suit, but I'm pretty pleased with the solution I came up with today! Additionally, really stoked I was able to figure out a recursive solution to this prompt as we only learned about recursion a couple weeks ago and I was worried I would get lost in the syntax.
The prompt was to write a function that starts at 0 and finds the first 25 numbers where the number plus its inverse equals a palindrome that is greater than 1000. Collect the 25 numbers in an array as the return value, do not collect the sum. Ok, what? That's a lot of information to unpack so let's get into the psuedocode.
- Write a function that takes in a number and finds palindromes.
- Start at 0.
- Use recursion, add 1 to the number each time.
- Each time through the function: is num + inverse > 1000? is sum (num + inverse) a palindrome? If yes, add num to array.
- Once the array has 25 numbers in it, return out of the function.
let first25 = []
const findPalindromes = (num) => {
const reverseIt = (num) => parseInt(num.toString().split('').reverse().join(''))
let sum = reverseIt(num) + parseInt(num)
if (first25.length >= 25) {
return
} else if (sum >= 1000 && sum === reverseIt(sum)) {
first25.push(num)
}
findPalindromes(num+1)
}
findPalindromes(0)
console.log(first25)
Do you have a different solution? I'd love to see!