程序说明
第一种方法用的是整数的处理。第二种方法用的是字符串处理。
代码如下:
#include <iostream>
using namespace std;
int main() {
int n, m;
cin>>n;
while(n) {
m = m * 10 + n % 10;
n /= 10;
}
cout<<m;
return 0;
}
字符串处理要考虑到前导零。
erase()方法删除某字符串特定字符。find_first_not_of()方法用于定位第一个不为零的数。注意负数的“ - ”不要在字符串中处理,因为如果“ - ”在字符串中,find_first_not_of()方法就不能正常使用了。
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main() {
string a, b;
getline(cin, a);
if(a[0] != '-') {
for(int i = a.size()-1; i >= 0; i--)
b += a[i];
if(b[0] == '0') {
b.erase(0, b.find_first_not_of('0'));
}
}
else {
for(int i = a.size()-1; i >= 1; i--)
b += a[i];
cout<<'-';
if(b[0] == '0')
b.erase(0, b.find_first_not_of('0'));
}
cout<<b<<endl;
return 0;
}