Skip to content

Instantly share code, notes, and snippets.

@AndrewVos
Created April 29, 2013 23:10
Show Gist options
  • Save AndrewVos/5485552 to your computer and use it in GitHub Desktop.
Save AndrewVos/5485552 to your computer and use it in GitHub Desktop.
require "benchmark"
def reverse number
inverse = 0
while number > 0
inverse = inverse * 10 + (number % 10)
number = number / 10
end
inverse
end
def is_palindrome_1? number
number == reverse(number)
end
def is_palindrome_2? number
number == number.reverse
end
numbers = 1.upto(99_999_999_999).to_a
strings = 1.upto(99_999_999_999).map {|n| n.to_s}
puts Benchmark.measure {
numbers.each do |n|
is_palindrome_1?(Integer(n))
end
}
puts Benchmark.measure {
strings.each do |n|
is_palindrome_2?(n)
end
}
#=> 8.710000 0.010000 8.720000 ( 8.711596)
#=> 2.940000 0.080000 3.020000 ( 3.036482)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment