Find Palindrome With Fixed Length LeetCode solution in C++

1
#define ll long long
2
class Solution {
3
public:
4
vector<long long> kthPalindrome(vector<int> &queries, int intLength) {
5
vector<ll> result;
6
ll start = intLength % 2 == 0 ? pow(10, intLength / 2 - 1) : pow(10, intLength / 2);
7
for (int q : queries) {
8
string s = to_string(start + q - 1);
9
string palindrome = s;
10
reverse(s.begin(), s.end());
11
if (intLength % 2 == 0) {
12
palindrome += s;
13
} else {
14
palindrome += s.substr(1, s.size() - 1);
15
}
16

17
// len of palindrome should be intLength, otherwise -1
18
if (palindrome.size() == intLength)
19
result.push_back(stoll(palindrome));
20
else
21
result.push_back(-1);
22
}
23

24
return result;
25
}
26
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0