PAT (Advanced Level) 1024. Palindromic Number (25)

手动模拟加法高精度。

注意:如果输入数字的就是回文,这个时候输出0步。

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<map>
#include<queue>
#include<vector>
using namespace std;

char s[120],t[120],c[120];
int tep;

void f(char *x)
{
    int len=strlen(x);
    for(int i=0; i<len/2; i++) swap(x[i],x[len-i-1]);
}

bool work()
{
    strcpy(t,s);
    f(t);
    int k=0;
    int len=strlen(s);
    int num1,num2;

    memset(c,0,sizeof c);

    for(int i=0; i<=len; i++)
    {
        if(s[i]==0) num1=num2=0;
        else num1=s[i]-'0',num2=t[i]-'0';
        c[i]=(num1+num2+k)%10+'0';
        k=(num1+num2+k)/10;
    }
    if(c[len]=='0') c[len]=0;
    f(c);

    int lenc=strlen(c);
    for(int i=0; i<lenc; i++)
        if(c[i]!=c[lenc-i-1]) return 0;
    return 1;
}

int main()
{
    memset(s,0,sizeof s);
    memset(t,0,sizeof t);

    scanf("%s",s);
    scanf("%d",&tep);

    int sz=strlen(s);

    bool fail=0;
    for(int i=0; i<sz; i++)
        if(s[i]!=s[sz-i-1]) fail=1;
    if(fail==0)
    {
        printf("%s
",s);
        printf("%d
",0);
    }
    else
    {
        bool flag=0;

        for(int i=1; i<=tep; i++)
        {
            if(work())
            {
                printf("%s
",c);
                printf("%d
",i);
                flag=1;
                break;
            }
            strcpy(s,c);
        }

        if(flag==0)
        {
            printf("%s
",c);
            printf("%d
",tep);
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zufezzt/p/5503224.html