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.
Example 1:
Input: queries = [1,2,3,4,5,90], intLength = 3 Output: [101,111,121,131,141,999] Explanation: The first few palindromes of length 3 are: 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ... The 90th palindrome of length 3 is 999.
Example 2:
Input: queries = [2,4,6], intLength = 4 Output: [1111,1331,1551] Explanation: The first six palindromes of length 4 are: 1001, 1111, 1221, 1331, 1441, and 1551.
Constraints:
1 <= queries.length <= 5 * 104
1 <= queries[i] <= 109
1 <= intLength <= 15
function kthPalindrome(queries: number[], intLength: number): number[] {
const isOdd = intLength % 2 === 1;
const bestNum = 10 ** ((intLength >> 1) + (isOdd ? 1 : 0) - 1);
const max = bestNum * 9;
return queries.map(v => {
if (v > max) {
return -1;
}
const num = bestNum + v - 1;
return Number(
num +
(num + '')
.split('')
.reverse()
.slice(isOdd ? 1 : 0)
.join(''),
);
});
}
impl Solution {
pub fn kth_palindrome(queries: Vec<i32>, int_length: i32) -> Vec<i64> {
let is_odd = int_length & 1 == 1;
let best_num = i32::pow(10, (int_length / 2 + if is_odd { 0 } else { -1 }) as u32);
let max = best_num * 9;
queries
.iter()
.map(|&num| {
if num > max {
return -1;
}
let num = best_num + num - 1;
format!(
"{}{}",
num,
num.to_string()
.chars()
.rev()
.skip(if is_odd { 1 } else { 0 })
.collect::<String>()
)
.parse()
.unwrap()
})
.collect()
}
}