样例过了,但是全WA,求助!

P1015 [NOIP1999 普及组] 回文数

Shrimp123 @ 2024-02-07 16:03:58

#include<bits/stdc++.h>
using namespace std;

int times=1;
int n;
string add(string a,string b) {
    if(a.length()<b.length())return add(b,a);
    reverse(a.begin(),a.end());
    reverse(b.begin(),b.end());
    int lena=a.length();
    int lenb=b.length();
    string sum;
    int t=0;
    int k=0;
    for(int i=0; i<lenb||i<lena; i++) {
        k=0;
        if(i<lena)k+=a[i]-'0';
        if(i<lenb)k+=b[i]-'0';
        sum+=(k%n+t)+'0';
        t=k/n;
    }
    if(t>0)sum+=t+'0';
    reverse(sum.begin(),sum.end());
    return sum;
}

bool judge(string a) {
    int len=a.length();
    for(int i=0; i<len/2; i++) {
    if(a[i]!=a[len-i-1])return 0;
    }
    return 1;
}

int f(string a,string b) {
    string i=add(a,b);
    cout<<i<<" ";
    if(judge(i)) {
        cout<<"STEP="<<times;
        return 0;
    }
    if(times>=30) {
        cout<<"Impossible!"<<endl;
        return 0;
    }
    string j=i;
    reverse(j.begin(),j.end());
    times++;
    return f(i,j);
}

int main()
{
    string m;
    cin>>n>>m;
    string w=m;
    reverse(w.begin(),w.end());
    f(m,w);
    return 0;
}

by juruo5e59 @ 2024-02-21 22:01:33

    string i=add(a,b);
    cout<<i<<" ";
    if(judge(i)) {

@Shrimp123中间不能输出i


by juruo5e59 @ 2024-02-21 22:06:27

而且f函数类型要用void,因为他没有返回值,函数内部要返回可以写以下语句

return;

by juruo5e59 @ 2024-02-21 22:07:28

要更新可以写个循环


by juruo5e59 @ 2024-02-21 22:10:43

    if(times>=30) {
        cout<<"Impossible!"<<endl;
        return 0;
    }

这里是times>30,见原文“如果在30步以内(包含30步)不可能得到回文数,则输出Impossible!”


|