Find the largest palindrome made from the product of two 3-digit numbers.
-----
First, I defined a palindrome recursively: a number is one if its first and last digits are the same, and if the inside is also a palindrome.
def palindrome?(digitArr)
if digitArr.empty?
true
elsif digitArr.length == 1
true
else
(digitArr.first == digitArr.last && palindrome?(digitArr[1..-2]))
end
end
Note that in Ruby, methods can end with a question mark, a convention that really helps readability. Also note that the "else if" keyword is elsif, which is weird and unhelpful to me. I want that 20 minutes of staring at my code like "wtf?!" (before figuring that out) back.
Then we do a search of all the multiples of two three-digit numbers until we find the biggest palindrome:
def search(i,j)
maxPal=0
while i > 99 do
j=999
while j > 99 do
if palindrome?((i*j).to_s.split("")) then
if(i*j)> maxPal then maxPal = i*j
end
end
j-=1
end
i-=1
end
return maxPal
end
puts search(999,999)
There's probably a prettier way to do this.