75分求助

P1015 [NOIP1999 普及组] 回文数

panrong @ 2024-03-19 19:21:18


#include <bits/stdc++.h>
using namespace std;
char a1[110];
int a[300],b[300],c[300];
bool hw(int m){
    for(int i=0;i<m;i++){
        if(c[i]!=c[m-i-1]) return 0;
    }
    return 1;
}
int main(){
    int n;
    cin>>n>>a1;
    int len=strlen(a1);
    for(int i=0;i<len;i++){
        if(a1[i]>='0'&&a1[i]<='9'){
            a[i]=a1[len-1-i]-'0';
            b[i]=a1[i]-'0';
        }
        else{
            a[i]=a1[len-1-i]-'A'+10;
            b[i]=a1[i]-'A'+10;
        }
        c[i]=b[i];
    }
    if(hw(len)==1){
        cout<<0;
        return 0;
    }
    for(int i=1;i<=30;i++){
        int x=0;
        for(int j=0;j<len;j++){
            c[j]=a[j]+b[j]+x;
            x=c[j]/n;
            c[j]%=n;
        }
        if(x) c[len++]=x;
        if(hw(len)==1){
            cout<<"STEP="<<i;
            return 0;
        }
        for(int j=0;j<len;j++){
            a[j]=c[len-1-j];
            b[j]=c[j];
        }
    }
    cout<<"Impossible!";
    return 0;
}

by Faded_wind123 @ 2024-04-14 00:13:55

@panrong 和楼主差不多,请问楼主知道问题出在哪里吗,我的代码如下


#include <iostream>
#include <string>

using namespace std;

int hw(string a) {
    int l = a.size();
    for (int i = 0; i < l / 2; i++) {
        if (a[i] != a[l - 1 - i]) {
            return 0;
        }
    }
    return 1;
}

string add(string a, string b, int jz) {
    int l1 = a.size(), l2 = b.size();
    if (l1 > l2) {
        b = string(l1 - l2, '0') + b;
    }
    if (l1 < l2) {
        a = string(l2 - l1, '0') + a;
    }
    int cf = 0, temp = 0;
    string c;
    int f = max(l1, l2);
    for (int i = 0; i < f; i++) {
        temp = a[f - 1 - i] + b[f - 1 - i] + cf - 2 * '0';
        cf = temp / jz;
        temp %= jz;
        c = char(temp + '0') + c;
    }
    if (cf != 0) {
        c = char(cf + '0') + c;
    }
    return c;
}

string change(string a) {
    string b;
    for (int i = a.size() - 1; i >= 0; i--) {
        b += a[i];
    }
    return b;
}

int main() {
    int k;
    string a;
    cin >> k >> a;
    int step = 0;

    do {
        if (hw(a)) {
            cout << step;
            return 0;
        }

        a = add(a, change(a), k);
        step++;
    } while (step <= 30);

    cout << "Impossible!";
    return 0;
}

|