输出1到最大n位数之间的所有数
2024-08-30 00:40:26
比如
n = 2
那么从1一直输出到99
分析
直接输出,遇到大数时肯定有问题,比如n=100,存储100位的数据类型不存在。
可以利用数组来存储大数,比如n=100,可以开辟个数组 char a[101]
思路一
模拟现实中的技术方式,逢九进一
参考代码
#include <iostream>
#include <cstring>
using namespace std; bool minuxOne(char *a, int *end_index, int size)
{
if((*end_index == size - && a[size - ] == '') || *end_index < || *end_index >= size)
return false;
int tmp = size - ;
if(a[size - ] != '')
--a[size -];
else
{
a[size - ] = '';
while()
{
if(a[tmp] == '')
{
a[tmp] = '';
--tmp;
}
else
{
--a[tmp];
break;
}
}
if(a[*end_index] == '')
++*end_index;
}
return true;
} bool printNum(const int size)
{
if(size < )
return false;
char *a = new char[size];
memset(a, '', size);
int end_index = ;
while()
{
if(end_index == size - && a[size - ] == '')
break;
for(int i = ; i < size; ++i)
{
if(end_index > i && a[i] == '' )
continue;
cout << a[i];
}
cout << "\t";
if(!minuxOne(a, &end_index, size))
break;
}
delete []a;
return true;
} int main()
{
int size = ;
printNum(size);
}
结果
思路二
本质可以看作是全排列,只是前边的0别输出
#include <iostream>
using namespace std; bool print1ToMaxN(const int n);
bool print1ToMaxNRecursion(char *a, int size, int index);
bool printNum(char *a, int size);
int main()
{
int size = ;
print1ToMaxN(size);
} bool print1ToMaxN(const int size)
{
if(size <= )
return false;
char *a = new char[size];
for(int i = ; i <= ; ++i)
{
a[] = i + '';
print1ToMaxNRecursion(a, size, );
}
return true;
} bool print1ToMaxNRecursion(char *a, int size, int index)
{
if(size <= || index < )
return false;
if(index == size)
{
printNum(a, size);
return true;
}
for(int i = ; i <= ; ++i)
{
a[index] = i + '';
print1ToMaxNRecursion(a, size, index + );
}
} bool printNum(char *a, int size)
{
if(size <= )
return false;
bool IsPre0 = true;
for(int i = ; i < size; ++i)
{
if(IsPre0 && a[i] != '')
IsPre0 = false;
if(!IsPre0)
cout << a[i];
}
cout << "\t";
}
结果
分析
1. 输出问题:一开始为0不要输出,这需要输出时判断下
2. 递归全排列的本质原理:每一位字符0~0都有可能,在方位本位的时候递归遍历下一位。
最新文章
- C#学习
- RTMP流媒体播放过程
- android去掉滑动到顶部和底部的阴影
- git 证书错误
- Java中request请求之 - 带文件上传的form表单
- http请求的referer属性
- Extjs4.2纯前台导出Excel总结
- VC/MFC 下 递归遍历目录下的所有子目录及文件
- scrollview上面的图片不上下滑动
- CodeChef Little Elephant and Mouses [DP]
- UI设计师给的px尺寸单位,安卓如何换算成dp?
- mysql 备份数据语句
- ansible的安装部署及简单应用
- 注解图Annotation
- js区别手机和电脑打开网页
- Python六大开源框架对比:Web2py略胜一筹(转)
- linux、内核源码、内核编译与配置、内核模块开发、内核启动流程(转)
- python3----requests
- 第23课 #error和#line使用分析
- 【MySQL解惑笔记】忘记MySQL数据库密码
热门文章
- 团队作业php
- Could not load file or assembly &#39;Microsoft.Office.Interop.Word, Version=14.0
- MVC缓存技术
- shell中的比较语句
- winform 如何控制输入法
- Load hlsl
- Nodejs Express 4.X 中文API 4--- Router篇
- PE文件结构详解
- Goolg Chrome 插件开发--Hello world
- 将HTMLCollection/NodeList/伪数组转换成数组