首页 > 其他 > 详细

剑指offer——18打印从1到最大的n位数

时间:2019-10-11 22:10:44      阅读:69      评论:0      收藏:0      [点我收藏+]

题目:

输入数字n,按顺序打印出从1到最大的n位十进制数。比如输入3,则打印出1、2、3一直到最大的3位数999。

题解:

  注意大数溢出问题,故使用字符串更靠谱

 

 1 class Solution
 2 {
 3 public:
 4     void Print1ToMaxOfNDigits(int n)
 5     {
 6         if (n < 1)
 7         {
 8             cout << 0 << endl;
 9             return;
10         }
11         string str = "1";
12         while(str.length()<n+1)
13         {
14             cout << str << endl;
15             int c = 0;            
16             for (int i = str.length() - 1; i >= 0; --i)
17             {
18                 if (i == str.length() - 1 || c == 1)
19                 {
20                     int temp = str[i] - 0 + 1;
21                     str[i] = temp % 10 + 0;
22                     c = temp / 10;
23                 }
24                 else
25                     break;
26             }
27             if (c == 1)
28                 str.insert(str.begin(), 1);
29         }
30     }
31 };

 

剑指offer——18打印从1到最大的n位数

原文:https://www.cnblogs.com/zzw1024/p/11657157.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!