#80分,求助

P1307 [NOIP2011 普及组] 数字反转

SakuraDeath @ 2020-12-08 14:20:27

#include<string>
#include<iostream>
using namespace std;
int main() {
    string str;
    cin >> str;
    int len = str.length();
    if (str[0] == '-') {
        cout << "-";
        for (int i = len-1; i >0; i--) {
            if( (i == len - 1) && str[i] == '0')
                continue;
            cout << str[i];
        }
    }
    else{
        for (int i = len-1; i >=0; i--) {
            if ((i == len - 1) && str[i] == '0')
                continue;
            cout << str[i];
        }
    }
    if (str[0] == '0') {
        cout << "0" << endl;
    }
    return 0;
}

by wenlebo @ 2022-02-15 11:10:29

错点:(i == len - 1) && str[i] == '0'

只能规避一个首0

改成这样:

#include<string>
#include<iostream>
using namespace std;
int main() {
    int q=1;//改点一
    string str;
    cin >> str;
    int len = str.length();
    if (str[0] == '-') {
        cout << "-";
        for (int i = len-1; i >0; i--) {
            if( (i == len - q) && str[i] == '0'){//改点2
                q++; 
            }else{
                cout << str[i];
        }////
        }
    }
    else{
        for (int i = len-1; i >=0; i--) {
            if ((i == len - q) && str[i] == '0'){//改点三
                q++;
            }else{
             cout << str[i];
        }///////
        }
    }
    if (str[0] == '0') {
        cout << "0" << endl;
    }
    return 0;
}

|