用 Python 生成前 n 個字典序數的程式


假設我們有一個數字 n,我們必須找出按字典序排序的前 n 個數字。

因此,如果輸入為 n = 15,則輸出將為 [1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]

為了解決這個問題,我們將按照以下步驟操作

  • count := 1
  • ans := 一個包含單元素 count 的列表
  • 當 ans 的大小 < n 時,執行
    • count := count * 10
    • 當 count > n 時,執行
      • count := count 的商除以 10
      • count := count + 1
      • 當 count 模 10 等於 0 時,執行
        • count := count 的商除以 10
      • 在 ans 末尾插入 count
  • 返回 ans

讓我們看一下以下實現來獲得更好的理解

示例程式碼

即時演示

class Solution:
   def solve(self, n):
      count = 1
      ans = [count]

      while len(ans) < n:
         count *= 10
         while count > n:
            count = count // 10
            count += 1
            while count % 10 == 0:
               count = count // 10
               ans.append(count)
            return ans

ob = Solution()
n = 15
print(ob.solve(n))

輸入

15

輸出

[1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]

更新於: 25-11-2020

295 次瀏覽

啟動您的職業生涯

完成課程,獲得認證

開始
廣告