蒟蒻求助!!

P1307 [NOIP2011 普及组] 数字反转

luogufather @ 2022-07-23 18:19:19

#include<bits/stdc++.h>
using namespace std;
int n;
string in;
int main()
{
    cin>>in;
    if(in[0]=='-')
{
cout<<'-';
}
    for(int i=in.length()-1;i>=0;i--)
    {
    //  if(in[0]=='-')
        if(in[in.length()-1]=='0')
        {
            cout<<in[i-1];
        }

            else cout<<in[i];
    //  }

    }
    return 0;
}

输入末尾是0的负数时,输出最后总有一个负号,不知道怎么去掉


by AfterFullStop @ 2022-07-23 18:23:29

问题在这:

for(int i=in.length()-1;i>=0;i--)
i>=0

当它是负数时,in[0]='-'啊

建议特判


by AfterFullStop @ 2022-07-23 18:23:42

@luogufather


by detor @ 2022-07-24 22:33:22

加一个特判,当是负数&&i==0时不输出


by lixuhui20120805 @ 2022-08-16 13:22:55

#include<bits/stdc++.h>
using namespace std;
int n,sum;
int main(int argc, char** argv) {
    scanf("%d",&n);
    if(n<0){//如果n为负数
        cout<<"-";//那么输出负号
        n=-n;
    }
    while(n){
        sum=sum*10+n%10;//数的个位相当于新数的最高位(除十取余法)
        n/=10;
    }
    cout<<sum<<endl;
    return 0;
}

by lixuhui20120805 @ 2022-08-16 13:23:25

@luogufather


by luogufather @ 2022-08-16 17:24:05

@lixuhui20120805 xiexei


by lixuhui20120805 @ 2022-08-16 17:35:30

@luogufather 甭客气


|