Created
April 29, 2013 23:10
-
-
Save AndrewVos/5485552 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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