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.)


In [1]:
def reverse(s):
    """
    Return the reverse of string 's'.
    """
    return s[::-1]

def is_palindrome(s):
    return s == reverse(s)

def binary_str(n):
    """
    Reference https://stackoverflow.com/questions/699866/python-int-to-binary
    """
    return "{0:b}".format(n)

In [2]:
s = 0
for i in range(1000000):
    if is_palindrome(str(i)) and is_palindrome(binary_str(i)):
        s += i
print("Sum of all numbers under 1000000 that is palindromic in base 10 and base 2 is", s)


Sum of all numbers under 1000000 that is palindromic in base 10 and base 2 is 872187