Topic describes

Enter the number n to print out the largest n decimal digits in sequence. For example, if you type 3, you print 1, 2, 3 up to 999.

Example 1:

Input: n = 1 Output: [1,2,3,4,5,6,7,8,9]Copy the code

Description:

  • Return a list of integers instead of printing
  • N is a positive integer

solution

Python3

class Solution:
    def printNumbers(self, n: int) -> List[int]:
        return [i for i in range(1, 10 ** n)]
Copy the code

Java

class Solution { public int[] printNumbers(int n) { n = (int) Math.pow(10, n) - 1; int[] res = new int[n]; for (int i = 0; i < n; ++i) { res[i] = i + 1; } return res; }}Copy the code

JavaScript

/**
 * @param {number} n
 * @return {number[]}
 */
var printNumbers = function (n) {
  let res = [];
  for (let i = 1; i < 10 ** n; ++i) {
    res.push(i);
  }
  return res;
};
Copy the code

C++

If n is large, you need a DFS enumeration and return a string

class Solution { public: vector<int> printNumbers(int n) { vector<int> ans; string s; dfs(ans, s, 0, n); return ans; } void dfs(vector<int>& ans, string& s, int k, int n) { if (k == n) { int num = atoi(s.c_str()); if (num) ans.push_back(num); return; } for (int i = 0; i <= 9; ++i) { s += i + '0'; dfs(ans, s, k + 1, n); s.pop_back(); }}};Copy the code