面试题17

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

示例 1:

输入: n = 1
输出: [1,2,3,4,5,6,7,8,9]

说明:

  • 用返回一个整数列表来代替打印

  • n 为正整数

Solutions

  1. pow(10, n)

  2. Follow up of the previous problem.

class Solution {
public:
    vector<int> printNumbers(int n) {
        int x = 10;
        int maxn = 1;
        // or maxn = pow(10, n) - 1
        while (n) {
            if (n & 1)
                maxn *= x;
            x *= x;
            n >>= 1;
        }
        vector<int> res(maxn - 1);
        for (int n = 1; n < maxn; n++)
            res[n - 1] = n;

        return res;
    }
};

or

class Solution {
public:
    vector<int> printNumbers(int n) {
        int maxn = pow(10, n) - 1;
        vector<int> res(maxn);
        iota(res.begin(), res.end(), 1);
        return res;
    }
};

Last updated

Was this helpful?