【题目】
输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数 999。
来源:leetcode
链接:https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/
【示例1】
输入: n = 1
输出: [1,2,3,4,5,6,7,8,9]
【说明】
1、用返回一个整数列表来代替打印
2、n 为正整数
【思路】
【代码】
耗时:12ms 62.26%
内存:11.2MB 100%
class Solution {
public:
vector<int> printNumbers(int n) {
long long x=1;
vector<int> v;
while(n--){
x*=10;
}
for(int i=1;i<x;i++)
v.push_back(i);
return v;
}
};
【改进】
用pow()函数代替上一个代码的while
执行用时 :8 ms, 在所有 C++ 提交中击败了87.37% 的用户
内存消耗 :11.5 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
vector<int> printNumbers(int n) {
int x=pow(10,n);
vector<int> v;
for(int i=1;i<x;i++)
v.push_back(i);
return v;
}
};