Talk is cheap, show me the code.
一、问题描述
输入一个整数,将这个整数以字符串的形式逆序输出
程序不考虑负数的情况,若数字含有0,则逆序形式也含有0,如输入为100,则输出为001
输入描述:
输入一个int整数
输出描述:
将这个整数以字符串的形式逆序输出
输入例子:
1516000
输出例子:
0006151
二、问题分析
有多种方法,可以直接读入一个字符串,然后对字符串倒序,可以用标准库algorithm中的reverse方法,或者直接用反向迭代器反向输出。也可以读入一个整数,然后分别取数,保存在一个字符串中,因为末位的0反向输出时在首位不能去掉,所以必须使用字符串来保存反向后的数。另外,还有一点值得注意,就是当输入的整数为0时,这个特殊情况需要特殊考虑。
解题方式1:
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
string s;
while (cin >> s)
{
reverse(s.begin(), s.end());
cout << s << endl;
}
return 0;
}
解题方式2:
#include <iostream>
#include <string>
#include <iterator>
using namespace std;
int main()
{
string s;
while (cin >> s)
{
string str;
for (string::reverse_iterator it = s.rbegin(); it != s.rend(); ++it)
{
str += (*it);
}
cout << str << endl;
}
return 0;
}
解题方式3:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a;
while (cin >> a)
{
if (a == 0)
cout << a << endl;
string s;
while (a)
{
int temp = a % 10;
s += (temp + '0');
a /= 10;
}
cout << s << endl;
}
return 0;
}