Strictly Palindromic Number

To determine whether a given number n is strictly palindromic, we must check that its representation in each base from 2 to n - 2 (inclusive) is palindromic. A number is palindromic if its representation reads the same forward and backward.

To convert a number to a given base, we can repeatedly divide the number by the base, recording the remainder at each step, and then reverse the list of remainders to obtain the number’s representation in that base.

Here’s the code to check if n is strictly palindromic:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def isStrictlyPalindromic(self, n: int) -> bool:
        def convert_to_base(number, base):
            digits = []
            while number > 0:
                digits.append(number % base)
                number //= base
            return digits[::-1]

        for base in range(2, n - 1):
            representation = convert_to_base(n, base)
            if representation != representation[::-1]:
                return False
        return True

Here’s a breakdown of the code:

  • The convert_to_base function converts a given number to the specified base and returns the result as a list of digits.
  • In the main function, we loop through each base from 2 to n - 2, converting n to that base and checking if the result is palindromic. If we find any non-palindromic representation, we return False.
  • If no non-palindromic representations are found, we return True.