spoj 5 PALIN - The Next Palindrome

PALIN - The Next Palindrome


A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.

Input

The first line contains integer t, the number of test cases. Integers K are given in the next t lines.

Output

For each K, output the smallest palindrome larger than K.

Example

Input:
2
808
2133

Output:
818
2222

Warning: large Input/Output data, be careful with certain languages

参考:

将问题分为以下五种情况:

  1. 如果所给的数全部由 9 组成,则输出 10…01 ,这里 0 的个数比 9 的个数少一个。(第 22 行,第 49 到 53 行的 IsWhole9s 方法,第 29 到 34 行的 Out 方法)
  2. 否则,如果所给的数只有一位数,则输出下一个数字。(第 23 行)
  3. 否则,如果所给的数的左半边倒转过来大于右半边,则以左半边为基准输出回文数。(第 24 行,第 55 到 66 行的 IsLeftReverseLargerThanRight 方法,第 36 到 47 行的 Out 方法,第 68 到 73 行的 GetLeftReverse 方法)
  4. 否则,如果所给的数的位数是奇数,并且最中间一位数字小于 9 ,则将最中间一位数字加一,并以左半边为基准输出回文数。(第 25 行,第 36 到 47 行的 Out 方法)
  5. 否则,计算所给的数的左半边从低位算起的连续的 9 的个数,这些连续的 9 需要替换为 0 ,然后再将左半边最右侧的非 9 数字加一,以此为基准输出回文数。如果所给的数的位数是奇数,则最中间一位数字必定是 9,这个 9 也必须替换为 0 。(第 26 行,第 75 到 80 行的 GetLeftSuccessive9sCount 方法,第 36 到 47 行的 Out 方法)

除了第一种情况,所求的回文数的位数是和所给的数的位数是一样的。举例如下:

情况 1 2 3 4 5
输入 9 99.99 7 21.07 38756 1234567 123.456 45699.99654 1239456
输出 11 10001 8 21.12 38783 1235321 124.421 45700.00754 1240421

上表中的小数点只是为了标出数的最中间位置,请忽略之。

#include <cstdio>  
#include <cstring>  
  
const int maxn = 1000005;  
  
int n, num[maxn];  
char str[maxn];  
  
inline bool cmp() {  
    for(int i = 0; i < n; i++)  
        if(num[i] < str[i] - '0') return 1;  
        else if(num[i] > str[i] - '0') return 0;  
    return 1;  
}  
  
int main() {  
    int T; scanf("%d", &T);  
    while(T--) {  
        scanf("%s", str); n = strlen(str);  
        if(n == 1) {  
            if(str[0] == '9') printf("11\n");  
            else printf("%c\n", str[0] + 1);  
            continue;  
        }  
  
        for(int i = n >> 1; i >= 0; i--) num[i] = num[n - i - 1] = str[i] - '0'; num[n] = 0;  
  
        if(cmp()) {  
            int st = n >> 1; num[st]++;  
            for(int i = st; num[i] > 9; i++) {  
                num[i] = 0;  
                num[i + 1]++;  
                if(i == n - 1) n++;  
            }  
            for(int i = 0; i < st; i++) num[i] = num[n - i - 1];  
        }  
        for(int i = 0; i < n; i++) printf("%d", num[i]);  
        printf("\n");  
    }  
    return 0;  
}  




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值