感觉思路、逻辑乃至代码都没毛病,但处理不了负数

P1307 [NOIP2011 普及组] 数字反转

tangyiqi @ 2024-08-31 21:32:01

#include <bits/stdc++.h>
#define ii int
#define u using namespace std;
#define ll long long
#define f for
#define p printf
#define s scanf
#define re return
u
ll n,sum = 0;
ii main(){
    s("%d",&n);
    if(n>=0){
        while(n){
            sum = sum*10+n%10;
            n/=10;
        }
    }
    else {
        p("-");
        n = 0-n;
        while(n){
            sum = sum*10+n%10;
            n/=10;
        }
    }
    p("%d",sum);
    re 0;
}

by Henry2012 @ 2024-08-31 21:38:35

你的n,sum都是long long,但是你的输入和输出用的都是%d


by superLouis @ 2024-08-31 21:43:37

教你一个简单的方法,不用处理负数
求关注

#include<bits/stdc++.h>
using namespace std;
int n, s;
int main() {
    cin >> n;
    while(n) s = s * 10 + n % 10, n /= 10;
    cout << s << "\n";
    return 0;
}

负数默认处理了,而且不用开long long


by zhanghaoyu111 @ 2024-09-05 21:32:26

关于long long用%d能不能处理负数,我也不清楚,但经过大佬的熏陶,我发现还是不会~~


by ganyunrui @ 2024-10-05 17:49:02

求关

#include<bits/stdc++.h>
using namespace std;
char n[20];
int len,num;
int main(){
    scanf("%s",n);
    len=strlen(n);
    if(n[0]=='-'){
        printf("-");
        num=1;
    }
    while(n[len-1]=='0'&&len>1) len--;
    for(int i=len-1;i>=num;i--) printf("%c",n[i]);
    return 0;
}

|