How to find a list of numbers up to a limit that is a palindrome in base 10 and base 2 in Python

1 Answer

0 votes
# Function to check if a number is a palindrome in a given base
def is_palindrome(num: int, base: int) -> bool:
    if base < 2:
        return False  # Invalid base

    strnum_reversed = []
    temp = num

    # Convert number to string in given base
    while temp > 0:
        digit = temp % base
        strnum_reversed.append(chr(ord('0') + digit) if digit < 10 else chr(ord('A') + (digit - 10)))
        temp //= base

    # Check palindrome
    return strnum_reversed == strnum_reversed[::-1]


limit = 1000

print("Numbers that are palindromes in both base 10 and base 2:")
for i in range(1, limit + 1):
    if is_palindrome(i, 10) and is_palindrome(i, 2):
        print(f"{i} (binary: ", end='')

        # Print binary representation
        binary = []
        temp = i
        while temp > 0:
            binary.append('1' if temp % 2 else '0')
            temp //= 2
        binary_str = ''.join(reversed(binary))

        print(f"{binary_str})")



"""
run:

Numbers that are palindromes in both base 10 and base 2:
1 (binary: 1)
3 (binary: 11)
5 (binary: 101)
7 (binary: 111)
9 (binary: 1001)
33 (binary: 100001)
99 (binary: 1100011)
313 (binary: 100111001)
585 (binary: 1001001001)
717 (binary: 1011001101)

"""

 



answered Nov 11 by avibootz
edited Nov 11 by avibootz
...