将一串数字逆转
输入123456
输出654321
循环解法
#include<iostream>
using namespace std;
int reverse(int a)
{
int temp = 0;
int i;
while (a)
{
i = a % 10;
temp = temp * 10 + i;
a = a / 10;
}
return temp;
}
int main()
{
int a = 1234566;
int res=reverse(a);
cout << res << endl;
system("pause");
}
递归
#include<iostream>
using namespace std;
int reverse(int num,int newnum)
{
if (num == 0)
{
return newnum;
}
else
{
newnum = newnum * 10 + num % 10;
//循环趋于终止,放在参数调用,newnum保存中间结果
reverse(num / 10,newnum);//保存中间数据
}
}
int main()
{
int input;
cin >>input;
int res = reverse(input,0);
cout << res << endl;
system("pause");
}