Skip to content

2396. Strictly Palindromic Number

Description

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

Solutions

Solution 1: Quick Thinking

When $n = 4$, its binary representation is $100$, which is not a palindrome;

When $n \gt 4$, its $(n - 2)$-ary representation is $12$, which is not a palindrome.

Therefore, we can directly return false.

The time complexity is $O(1)$, and the space complexity is $O(1)$.

1
2
3
class Solution:
    def isStrictlyPalindromic(self, n: int) -> bool:
        return False
1
2
3
4
5
class Solution {
    public boolean isStrictlyPalindromic(int n) {
        return false;
    }
}
1
2
3
4
5
6
class Solution {
public:
    bool isStrictlyPalindromic(int n) {
        return false;
    }
};
1
2
3
func isStrictlyPalindromic(n int) bool {
    return false
}
1
2
3
function isStrictlyPalindromic(n: number): boolean {
    return false;
}
1
2
3
4
5
impl Solution {
    pub fn is_strictly_palindromic(n: i32) -> bool {
        false
    }
}
1
2
3
bool isStrictlyPalindromic(int n) {
    return 0;
}

Comments