Created
March 11, 2012 18:53
-
-
Save larryv/2017667 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/env ruby1.9 | |
# Project Euler, Problem 36 | |
# | |
# The decimal number, 585 = 1001001001 (binary), is palindromic in both | |
# bases. | |
# | |
# Find the sum of all numbers, less than one million, which are palindromic | |
# in base 10 and base 2. | |
# | |
# (Please note that the palindromic number, in either base, may not include | |
# leading zeros.) | |
# | |
# Lawrence Velazquez | |
# 11 March 2012 | |
class Fixnum | |
def to_binary_s | |
bits = 63.downto(0).each_with_object("") {|i, str| str << self[i].to_s} | |
bits.sub(/^0+/, "") | |
end | |
def bipalindromic? | |
return false if self != self.to_s.reverse.to_i | |
self == self.to_binary_s.reverse.to_i(2) | |
end | |
end | |
puts 1.upto(999999).inject(0) {|sum, n| n.bipalindromic? ? sum + n : sum} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment