소프트웨어에 대한 모든 것

2396. Strictly Palindromic Number 본문

알고리즘/LeetCode

2396. Strictly Palindromic Number

앤테바 2022. 12. 23. 12:24
반응형

문제)

2396. Strictly Palindromic Number

 

An integer n is strictly palindromic if, for every base b between 2 and n - 2 (inclusive), the string representation of the integer n in base b is palindromic.

Given an integer n, return true if n is strictly palindromic and false otherwise.

A string is palindromic if it reads the same forward and backward.

 

Example 1:

Input: n = 9
Output: false
Explanation: In base 2: 9 = 1001 (base 2), which is palindromic.
In base 3: 9 = 100 (base 3), which is not palindromic.
Therefore, 9 is not strictly palindromic so we return false.
Note that in bases 4, 5, 6, and 7, n = 9 is also not palindromic.

Example 2:

Input: n = 4
Output: false
Explanation: We only consider base 2: 4 = 100 (base 2), which is not palindromic.
Therefore, we return false.

 

Constraints:

  • 4 <= n <= 105

 

솔루션1)

- 2부터 n-2까지 반복하면서 진수변환해서 palindrome를 체크

class Solution:
    def isStrictlyPalindromic(self, n: int) -> bool:        
        for i in range(2, n-1):
            val = self.convert_to_base_n(n, i)            
            if val != val[::-1]:
                return False
        return True
    
    def convert_to_base_n(self, num, n):
        ret = []
        while num:
            num, remainder = divmod(num, n)
            ret.append(str(remainder))        
        return ''.join(ret.reverse())

 

반응형

'알고리즘 > LeetCode' 카테고리의 다른 글

2265. Count Nodes Equal to Average of Subtree  (0) 2022.12.23
2433. Find The Original Array of Prefix Xor  (0) 2022.12.23
1476. Subrectangle Queries  (0) 2022.12.23
2465. Number of Distinct Averages  (0) 2022.12.23
504. Base 7  (0) 2022.12.23
Comments