[LeetCode] Find Palindrome With Fixed Length

2217. Find Palindrome With Fixed Length

Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists.

A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
long long to_long(string num, bool odd) {
string rev = num;
reverse(rev.begin(), rev.end());
if(odd) num.pop_back();
return stol(num+rev);
}
public:
vector<long long> kthPalindrome(vector<int>& queries, int intLength) {
int len = (intLength + 1) / 2;
long base = pow(10,len-1);
vector<long long> res;
for(auto& q : queries) {
string num = to_string(base + q - 1);
if(num.length() != len) {
res.push_back(-1);
} else {
res.push_back(to_long(num, intLength & 1));
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/28/PS/LeetCode/find-palindrome-with-fixed-length/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.