Created
November 8, 2017 19:36
-
-
Save dmgarland/e67f130587dafeb73ad54a0d3c2b9322 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
# The decimal number, 585 = 10010010012 (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 0's) | |
# Naive approach - TODO: needs to avoid checking both base 2 and base 10 if base 10 isn't pallindromic | |
def palindromic?(n, base = 10) | |
numbers = n.to_s(base).split("") | |
middle = numbers.length / 2.0 | |
first_half = numbers.slice(0, middle.ceil) | |
second_half = numbers.slice(middle.floor, numbers.length) | |
first_half == second_half.reverse | |
end | |
puts (1..1_000_000).select { |n| | |
[10, 2].all? { |base| palindromic?(n, base) } | |
}.inject(&:+) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment