手动输入没有发现怎么错的啊,麻烦帮忙看看

P1307 [NOIP2011 普及组] 数字反转

y1219323890 @ 2024-01-14 11:27:09

#include<iostream>
#include<math.h>
using namespace std;
int main(){
    int n;int cnt;
    int r;
    cin>>n;
    r=fabs(n);
    while(r>0){
        r=r/10;
        cnt++;
    }
    int v=cnt;
    r=fabs(n);
    if(n<0){
            cout<<"-";
    }
    if(n==0){
        cout<<n;
        return 0;
    }
    for(int i=0;i<cnt;i++){
        int k=r%10;
         if(cnt==v&&k==0){
            r=r/10;
            v--;
         }else{
            r=r/10;
            cout<<k;
            v--;
         }
    } 
    return 0;
} 

by Pitiless_boy @ 2024-01-14 11:34:40

r = abs(n)试一下


by Pitiless_boy @ 2024-01-14 11:37:57

这么改:

#include<bits/stdc++.h>
using namespace std;
int main() {
    int n;
    int r;
    cin >> n;
    int r = abs(n);
    if (n < 0)
        printf("-");
    n = abs(n);
    int pos = -1;
    while (n) {
        if (n % 10 != 0)
            pos = 1;
        if (n % 10 == 0 && pos != -1)
            printf("%d", n % 10);
        else
            if (n % 10 != 0)
                printf("%d", n % 10);
        n /= 10;
    }
}

by y1219323890 @ 2024-01-14 14:22:56

@Pitiless_boy 这样改好像最后一个测试点会错这样改好像就是对的直接不用math库了

#include<iostream>
#include<math.h>
using namespace std;
int main(){
    int n;int cnt;
    int r;int sum=0;
    cin>>n;
    r=fabs(n);

    while(r>0){
        r=r/10;
        cnt++;
    }

    int v=cnt;

    if(n<0){
            cout<<"-";
            n=-n;
    }

    if(n==0){
        cout<<n;
        return 0;
    }

    if(n%10==0){
        n=n/10;
    }

    while(n!=0){
            int k=n%10;
            sum=sum*10+k;
            n=n/10;
        } 
        cout<<sum;
    return 0;
} 


|