F - Palindrometer

Description

Download as PDF

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值