Now, onto Problem 4.
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.
First the tests:
require 'problem4/problem4' describe "largest palindrome" do it "finds the largest palindrome of 2 digit numbers" do expect(Problem4.answer(10...100)).to eq 9009 end it "finds the largest palendrome of 3 digit numbers" do expect(Problem4.answer(100...1000)).to eq 906609 end end
Now for the solution code:
module Problem4 def self.answer(largest_palindrome_range) max = 0 (largest_palindrome_range).each do |a| (a...largest_palindrome_range.end).each do |b| product = a*b max = [max, product].max if product.to_s == product.to_s.reverse end end return max end puts Problem4.answer(100...1000) end
So, first, I thought about a palindrome. A palindrome is the reverse of itself. So, I took the range we were testing and took each number to get a and then did the same from a to the end of the range to get b. Then I multiplied all of the resulting 2 number possibilities. Finally, in order to find the maximum, you take the product, convert it to a string and then see if it equals the reverse of the string.
This one was really tough for me. I knew about how to find the max and I knew how to check if it was a palindrome and reversing the string, but the middle section of finding the products via the range given was pretty challenging for me to wrap my head around.
No comments:
Post a Comment