
题目
解决代码及点评
/* 输入数字 n,按顺序输出从 1 最大的 n 位 10 进制数。比如输入 3,则输出 1、2、3 一直到最大的 3 位数即 999。 */ #include <iostream> using namespace std; //在不考虑大数的情况下,只要简单找出最大数,然后循环打印即可 void Print1(int n) { if (n <= 0) { return; } int nMax = 1; // 获得最大数 for (int i = 0; i < n; i++) { nMax *= 10; if (nMax > INT_MAX || nMax < INT_MIN) { return; } } // 循环打印即可 for (int i = 1; i < nMax; i++) { cout<<i<<endl; } } void PrintNumber(char *pszBuf, int nLen) { int i = 0; while(pszBuf[i] == '0') { i++; } while (i < nLen) { cout<<pszBuf[i]; i++; } cout<<" "; } void printRecurive(char *pszBuf, int nLen, int nIndex) { if (nLen == nIndex) { PrintNumber(pszBuf, nLen); } else { for (int i = 0; i <= 9; i++) { pszBuf[nIndex] = i + '0'; printRecurive(pszBuf, nLen, nIndex + 1); } } } // 如果要考虑大数,那么应该用字符串来表示数 void Print2(int n) { if (n <= 0) { return; } char *pszBuf = new char[n]; // 递归的打印 printRecurive(pszBuf, n, 0); } int main() { int n; cin>>n; Print2(n); system("pause"); return 0; }
代码下载及其运行
代码下载地址:http://download.csdn.net/detail/yincheng01/6704519
解压密码:c.itcast.cn
下载代码并解压后,用VC2013打开interview.sln,并设置对应的启动项目后,点击运行即可,具体步骤如下:
1)设置启动项目:右键点击解决方案,在弹出菜单中选择“设置启动项目”
2)在下拉框中选择相应项目,项目名和博客编号一致
3)点击“本地Windows调试器”运行
程序运行结果