题解 P5705 数字反转

· · 题解

这是洛谷入门赛的签到题,对于初学的新手来说,这显然是练习字符串的好机会

我们先来认识一下c++的字符串string,这个类型相当于c中char[],和char一样,string也可以用数组表示多个字符串,即string a[]。接下来看看常见的几个string类型操作:

string a;//定义一个string类字符串。

int len=a.size()//读取串a的长度,注意此时a中字符下标是从0开始的。

有了这些,我们便可以反转了!

#include<bits/stdc++.h>万能头文件
using namespace std;
string a;
signed main()
{
    cin>>a;
    int len=a.size();读取长度
    for(int i=len-1;i>=0;i--)反转
    cout<<a[i];
    return 0;
}

学会了吗,那么再看一道题: 练习

我们当然也可以使用字符串做出这道题,但是,我们需要处理前导0.那么,有没有什么方法可以无需处理前导0呢。或许我们可以直接对数字进行处理:

#include<bits/stdc++.h>
using namespace std;
int n,k;
int turn(int n);
int main()
{
cin>>n;
turn(n);
cout<<k<<endl;
return 0;
}

int turn(int n)
{
while(n)
{ 
    k=k*10 + n%10;
    n/=10;
}
return 0;
}

会了吗?自己试试吧!