题目表述:
输入一个非负整数,输出这个数的倒序。例如输入123,输出321。
输入:
一个个位不为0的非负整数。
输出:
倒序之后的数。
输入样例:123
输出样例:321
思路:
因为,我是按照递归算法的两个要素来做的,所以,
停止的条件: (因为这个比较好找)
n<0。(我想的是一个一个提取)
递归关系式: (这个我想了一短时间)
d(n)=(n%10)*10+d(n/10)
一开始,我以为是这样的。但是隐隐约约觉得不对劲。
于是,程序的雏形就打出来了。
#include<iostream> //使用iostream库
#include<cstdio> //使用cstdio库
using namespace std;
int d(int x) //运用递归的d函数
{
if(x<10) //停止的条件
return x;
else //递归关系式
return (x%10)*10+d(x/10);
}
int main() //主函数
{
int a;//要被倒序的数
cin>>a;//输入
cout<<d(a);//输出
return 0;
}
试验了之后,果然不对劲。
仔细一想:
123%10=3, 3*10=30, 123/10=12, 12%10=2, 2*10=30, 12/10=1,30+20+1=51
但是,
我想的是:
3*123的最高位=300+2*12的最高位=20+1=321
所以呢,要算出最高位才行,我查了一下,但并没有软件自带的这种函数,我就只能自己建一个自定义函数。
#include<iostream> //使用iostream库
#include<cstdio> //使用cstdio库
using namespace std;
int a(int y)//用来算最高为的函数
{
int i;
for(i=10;y/i>=10;i*=10)//一直缩位
{}
return i-1;//然后再减去一位输出
}
int d(int x) //运用递归的d函数
{
if(x<10) //停止的条件
return x;
else //递归关系式
return (x%10)*a(x)+d(x/10);
}
int main() //主函数
{
int a;//要被倒序的数
cin>>a;//输入
cout<<d(a);//输出
return 0;
}
?
?
难道这就对了吗?
?
?
当然不是
我又想了想,觉得函数d应该没有问题。目光又看向了函数a,for应该没问题,但return应该有问题,于是,就把,-1去掉了。
递归关系式最后就成了:
d(1)=1*1
d(12)=2*10+d(1)
d(123)=3*100+d(12)
#include<iostream> //使用iostream库
#include<cstdio> //使用cstdio库
using namespace std;
int a(int y)//用来算最高为的函数
{
int i;
for(i=10;y/i>=10;i*=10)//一直缩位
{}
return i;//最后输出
}
int d(int x) //运用递归的d函数
{
if(x<10) //停止的条件
return x;
else //递归关系式
return (x%10)*a(x)+d(x/10);
}
int main() //主函数
{
int a;//要被倒序的数
cin>>a;//输入
cout<<d(a);//输出
return 0;
}
?
?
这次会对吗?
?
?
噢噢噢噢噢噢噢噢噢噢噢
噢噢噢噢噢噢噢噢噢噢噢
噢噢噢噢噢噢噢噢噢噢噢
噢噢噢噢噢噢噢噢噢噢噢
噢噢噢噢噢噢噢噢噢噢噢
噢噢噢噢噢噢噢噢噢噢噢
噢噢噢噢噢噢噢噢噢噢噢
咱们接着测
最后
让网站来打个圆场