[AtCoder Beginner Contest 363] D - Palindromic Number

 

1. The 1st palindromic number is 0, so we do N-- to exclude 0.

2. F(k): the number of palindromic numbers of length k. F(1) = 9; F(2) = 9; F(k) = F(k - 2) * 10.

3. Use the above formula to get the length of the answer palindromic string, call it LEN. Using the formula we can also get the relative rank among all length LEN numbers, comparing to 100001, call this rank RANK. (Remeber to minus 1)

4. Now we just need to use the number 100 + RANK as the first half and construct the answer using it. This works because for two numbers X1 and X2 of the same length, if the first half of X1 > the first half of X2, X1 > X2. The same applies to <. 

 

 

    static void solve(int testCnt) {
        for (int testNumber = 0; testNumber < testCnt; testNumber++) {
            n = in.nextLong();
            if(n <= 10) {
                out.println(n - 1);
            }
            else if(n < 20) {
                out.println((n % 10 * 10) + (n % 10));
            }
            else {
                long m = n - 1;
                long d = 9;
                int digits = 1;
                while(m > d * 2) {
                    m -= d * 2;
                    d *= 10;
                    digits += 2;
                }
                if(m > d) {
                    m -= d;
                    digits++;
                }
                m--;
                long[] ans = new long[digits];
                for(int i = (digits - 1) / 2; i >= 0; i--) {
                    ans[i] = m % 10;
                    m /= 10;
                }
                ans[0]++;
                for(int i = 0; i <= (digits - 1) / 2; i++) {
                    ans[digits - 1 - i] = ans[i];
                }
                for(long x : ans) {
                    out.print(x);
                }
                out.println();
            }
        }
        out.close();
    }

 

posted @ 2024-07-22 02:21  Review->Improve  阅读(18)  评论(0编辑  收藏  举报