80分求调

P1307 [NOIP2011 普及组] 数字反转

RainbowRain @ 2024-10-21 20:48:39

#include <iostream>
using namespace std;

int main()
{
    long long N;
    cin >> N;
    if (N < 0)
    {
        cout << "-";
        N = -N;
    }
    if (N % 10 == 0)
        N = N / 10;
    while (N != 0)
    {
        cout << N % 10;
        N /= 10;
    }

    return 0;
}

by LBS6307 @ 2024-10-21 20:54:17

这题其实是字符串的题,你思路错了,反转后去掉前导零或者/然后加上-符号就行了嘛


by xywuyu @ 2024-10-21 20:58:15

@LBS6307 不一定吧


by xywuyu @ 2024-10-21 20:58:36

#include <iostream>
using namespace std;
int main()
{ int a,n=0;
cin>>a;
while (a!=0)
{n=n*10;
n=n+a%10;
a=a/10;}
cout<<n;

return 0;}

by Ff472130 @ 2024-10-21 20:59:10

加个特判0,还有前导0要多次判断,所以要用while

代码

#include <iostream>
using namespace std;

int main()
{
    long long N;
    cin >> N;
    if (N == 0){ //特判0 
        cout << 0;
        return 0;
    }
    if (N < 0)
    {
        cout << "-";
        N = -N;
    }
    while (N % 10 == 0) //处理前导0 
        N = N / 10;
    while (N != 0)
    {
        cout << N % 10;   
        N /= 10;
    }
    return 0;
}

求关


by RainbowRain @ 2024-10-21 20:59:56

我知道了,前导0我这里只满足一个,改一下就好了


by RainbowRain @ 2024-10-21 21:10:23

@Ff472130 可以的,感谢


by LBS6307 @ 2024-10-21 21:25:32

@xywuyu 也可以取模进另一个int数,见仁见智,反正我喜欢用字符串做这种反转/回文的题目?


by xywuyu @ 2024-10-21 21:30:42

@LBS6307 字符串做这种题确实简单哈,这道题输入然后直接倒序输出,省时省力


by xywuyu @ 2024-10-21 21:32:14

哦,忘了,还得判负数和0


by dingjingxuan1234 @ 2024-10-25 20:04:14

......简洁一些不好吗?

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

|