词典编号的逻辑

时间:2017-03-25 03:33:58

标签: c++ algorithm

对于整数n,我们必须按字典顺序返回1到n。下面是它的代码。我理解代码,但背后的逻辑是什么?

例如:给定13,返回:[1,10,11,12,13,2,3,4,5,6,7,8,9]。

class Solution {
    public:
        vector<int> lexicalOrder(int n) {
            vector<int> result(n);
            int curr = 1;
            for (int i = 0; i < n; i++) {
                result[i] = curr;
                if (curr * 10 <= n) {
                    curr *= 10;
                } else if (curr % 10 != 9 && curr + 1 <= n) {
                    curr += 1;
                } else {
                    while((curr / 10) % 10 == 9) {
                        curr /= 10;
                    }
                    curr = curr / 10 + 1;
                }
            }
            return result;

        }
    };

0 个答案:

没有答案