2217. Find Palindrome With Fixed Length

58 阅读1分钟

image.png

方法

image.png

class Solution {
    public long[] kthPalindrome(int[] queries, int intLength) {
        int l = (intLength + 1) / 2;
        long[] res = new long[queries.length];
        int j = 0;

        // find i-th largest number (left half)
        for (int i = 0; i < queries.length; i++) {
            String leftHalf = (int)Math.pow(10, l - 1) + queries[i] - 1 + "";
            StringBuilder sb = new StringBuilder(leftHalf);
            StringBuilder copy = new StringBuilder(sb);

            if (intLength % 2 == 0) {
                sb.append(copy.reverse());
            } else if (intLength % 2 == 1) {
                for (int k = copy.length() - 2; k >= 0; k--) {
                    sb.append(copy.charAt(k));
                }
            }
            
            // leftHalf * 2 length exceeds intLength
            if (sb.length() > intLength) {
                res[j] = -1;
            } else {
                res[j] = Long.parseLong(sb.toString());
            }
            j++;
        }
        return res;
    }
}