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

题目:

输入数字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 };

猜你喜欢

转载自www.cnblogs.com/zzw1024/p/11657157.html