[LeetCode] Strictly Palindromic Number

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
string baseK(int n, int k) {
string res = "";
while(n) {
res.push_back(n%k + '0');
n/=k;
}
return res;
}
bool palindrome(string s) {
int l = 0, r = s.size() - 1;
while(l < r) {
if(s[l++] != s[r--]) return false;
}
return true;
}
public:
bool isStrictlyPalindromic(int n) {
for(int i = 2; i <= n - 2; i++) {
if(!palindrome(baseK(n,i))) return false;
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/03/PS/LeetCode/strictly-palindromic-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.