F - Palindrometer

Description

While driving the other day, John looked down at his odometer, and it read 100000. John was pretty excited about that. But, just one mile further, the odometer read 100001, and John was REALLY excited! You see, John loves palindromes - things that read the same way forwards and backwards. So, given any odometer reading, what is the least number of miles John must drive before the odometer reading is a palindrome? For John, every odometer digit counts. If the odometer reading was 000121, he wouldn't consider that a palindrome.

Input

There will be several test cases in the input. Each test case will consist of an odometer reading on its own line. Each odometer reading will be from 2 to 9 digits long. The odometer in question has the number of digits given in the input so, if the input is 00456, the odometer has 5 digits. There will be no spaces in the input, and no blank lines between input sets. The input will end with a line with a single 0.

Output

For each test case, output the minimum number of miles John must drive before the odometer reading is a palindrome. This may be 0 if the number is already a palindrome. Output each integer on its own line, with no extra spaces and no blank lines between outputs.

Sample Input

100000 
100001 
000121 
00456 
0

Sample Output

1 
0 
979 
44
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 100001
#define INF 2000

using namespace std;

int zl[10];
int ans[N];
int a[10];
int tot,len;

int change(char s[])
{
    int ans=0;
    int len=strlen(s);
    for(int i=len-1;i>=0;i--)
        ans+=zl[len-i-1]*(s[i]-'0');
    return ans;
}
void dfs(int now)
{
    if(now==(len+1)/2)
    {
        for(int i=1;i<=(len+1)/2;i++)
            a[len+1-i]=a[i];
        ans[tot]=0;
        for(int i=1;i<=len;i++)
            ans[tot]+=a[i]*zl[i-1];
        tot++;
        return;
    }
    for(int i=0;i<10;i++)
    {
        a[now+1]=i;
        dfs(now+1);
    }
}
int main()
{
    zl[0]=1;
    for(int i=1;i<=9;i++) zl[i]=zl[i-1]*10;
    char s[10];
    while(gets(s),strcmp("0",s)!=0)
    {
        len=strlen(s);
        int now=change(s);
        memset(a,0,sizeof(a));
        tot=0;
        dfs(0);
        sort(ans,ans+tot);
        int i=0;
        while(ans[i]<now) i++;
        printf("%d\n",ans[i]-now);
    }
    return 0;
}


你可能感兴趣的:(F - Palindrometer)