Find Palindrome With Fixed Length LeetCode solution in JavaScript

1
var kthPalindrome = function (queries, intLength) {
2
let output = [];
3
// 1. We use FIRST 2 digits to create palindromes: Math.floor((3+1)/2)=2
4
let digit = Math.floor((intLength + 1) / 2);
5

6
for (let i = 0; i < queries.length; i++) {
7
// 2A. Get Nth 2-digits numbers: 10*(2-1)-1+[5,98]=[14,107]
8
let helper = 10 ** (digit - 1) - 1 + queries[i];
9
// 2B. Digits checking: 107>=100, which is INVALID
10
if (helper >= 10 ** digit) {
11
output.push(-1);
12
} else {
13
let m = intLength - digit;
14
// 3A. We still need m digits for REFLECTION: 14=>["1","4"]=>"41"
15
let add = helper.toString().substr(0, m).split("").reverse().join("");
16
// 3B. Multiply 10**m for reversed digits: 14=>1400=>1441
17
helper = helper * 10 ** m + add * 1;
18
output.push(helper);
19
}
20
}
21
return output; // [1441,-1]
22
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0