c++ - 给定一个整数 N,按字典顺序打印从 1 到 N 的数字

标签 c++ algorithm

我正在尝试按字典顺序打印从 1 到 N 的数字,但输出失败。对于以下输入 100,我得到了 100,但它发生了偏移并且与预期输出不匹配,我的代码中存在一个错误,但我无法追溯它。

class Solution {
public:
    vector<int> lexicalOrder(int n) {
         vector<int> result;
        for(int i = 1; i <= 9; i ++){
        int j = 1;
        while( j <= n){
            for(int m = 0; m < j ; ++ m){
                if(m + j * i <= n){

                    result.push_back(m+j*i);
                }
            }
            j *= 10;
        }
    }
    return result;

    }
};



Input:
100
Output:
[1,10,11,12,13,14,15,16,17,18,19,100,2,20,21,22,23,24,25,26,27,28,29,3,30,31,32,33,34,35,36,37,38,39,4,40,41,42,43,44,45,46,47,48,49,5,50,51,52,53,54,55,56,57,58,59,6,60,61,62,63,64,65,66,67,68,69,7,70,71,72,73,74,75,76,77,78,79,8,80,81,82,83,84,85,86,87,88,89,9,90,91,92,93,94,95,96,97,98,99]

Expected:
[1,10,100,11,12,13,14,15,16,17,18,19,2,20,21,22,23,24,25,26,27,28,29,3,30,31,32,33,34,35,36,37,38,39,4,40,41,42,43,44,45,46,47

最佳答案

想想当i=1,j=10时会发生什么

for(int m = 0; m < j ; ++ m){
                if(m + j * i <= n){

                    result.push_back(m+j*i);
                }
            }

是的,result 将 push_back 10(0+10*1),11(1+10*1),12(2+10*1).. 这是一个解决方案:

#include <iostream>
#include <vector>
#include <string>
std::vector<int> fun(int n)
{
        std::vector<std::string> result;
        for (int i = 1; i <= n; ++i) {
            result.push_back(std::to_string(i));
        }
        std::sort(result.begin(),result.end());
        std::vector<int> ret;
        for (auto i : result) {
            ret.push_back(std::stoi(i));
        }
        return ret;
}
int main(int argc, char *argv[])
{
        std::vector<int> result = fun(100);
        for (auto i : result) {
            std::cout << i << ",";
        }
        std::cout << std::endl;
        return 0;
}

关于c++ - 给定一个整数 N,按字典顺序打印从 1 到 N 的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39060106/

相关文章:

c++ - OpenALPR 退出并出现带有自定义训练数据的段错误

c++ - 需要提高断字速度的建议(动态规划)

c# - 快速计算传入数字的最小值、最大值和平均值

algorithm - 为什么我们在矩阵链乘法中使用三个循环?

algorithm - 从具有评级的人员列表中建立两人一组

c++ - std::map 通过变换替换现有元素

c++ - Qt5 SSL 支持

c++ - @selector 在C++中的实现

c - Dijkstra,Bellman Ford 在双阵列 map 上的应用

python - 缺少不应该缺少的参数(Python)?