zoukankan      html  css  js  c++  java
  • 剑指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 };
  • 相关阅读:
    context:component-scan报错
    goland 实用键
    React-Native 指定模拟器RUN-IOS
    mac 卸载编辑器卸不干净
    go 区分指针
    go 学习Printf
    我的命令行
    mysql8的坑
    小三角
    eslint 禁用命令
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11657157.html
Copyright © 2011-2022 走看看