“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 zeros.)”
Python just makes these too easy.
def is_palindrome(x): """ Returns true if the digits of x are the same both backward and forward in both base 2 and base 10. """ x10 = str(x) x2 = bin(x)[2:] return x10 == x10[::-1] and x2 == x2[::-1] # check only odd numbers since even base 2 numbers end in 0 >>> sum(filter(is_palindrome, range(1,1000000,2))) 872187 |
Tags: binary, palindrome, project euler, python