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.)
Iterate and check if is palindrome in base 10 and base 2.
No leading zeros means no tailing zeros, so cannot be even number. (Even number has tailing zero in base 2).
def is_palindrome_base10(n):
l = len(str(n))
for i in range(l // 2):
p = pow(10, l-2*i-1)
if n % 10 != n // p:
return False
n = (n % p) // 10
return True
is_palindrome_base10(1)
is_palindrome_base10(585)
is_palindrome_base10(123)
def is_palindrome_base2(n):
b = bin(n)[2:]
half = len(b) // 2
return n == 1 or b[:half] == ''.join(reversed(b[-half:]))
is_palindrome_base2(1)
is_palindrome_base2(5)
is_palindrome_base2(585)
is_palindrome_base2(123)
def is_doublebase_palindrome(n):
if n % 2 == 0:
return False
return is_palindrome_base10(n) and is_palindrome_base2(n)
is_doublebase_palindrome(585)
def solve(bound):
doublebase_palindromes = list(filter(is_doublebase_palindrome, range(1, int(bound))))
return sum(doublebase_palindromes), list(zip(doublebase_palindromes, map(lambda n: bin(n)[2:], doublebase_palindromes)))
solve(100)
solve(1e6)