Skip to content

顺次数-1291 #116

Description

@sl1673495

我们定义「顺次数」为:每一位上的数字都比前一位上的数字大 1 的整数。

请你返回由  [low, high]  范围内所有顺次数组成的 有序 列表(从小到大排序)。

示例 1:

输出:low = 100, high = 300
输出:[123,234]
示例 2:

输出:low = 1000, high = 13000
输出:[1234,2345,3456,4567,5678,6789,12345]

提示:

10 <= low <= high <= 10^9

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sequential-digits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

先通过 lowhigh之间的长度对比,得到总共有几种数字长度。

然后循环这些数字长度 len 作为目标, 1 作为最小起点, 10 - len 作为最大的起点,不断尝试构造出长度为 len 的顺位数字即可。

/**
 * @param {number} low
 * @param {number} high
 * @return {number[]}
 */
let sequentialDigits = function (low, high) {
  let lowLen = low.toString().length
  let highLen = high.toString().length
  let lens = []
  for (let i = lowLen; i <= highLen; i++) {
    lens.push(i)
  }

  let res = []
  for (let i = 0; i < lens.length; i++) {
    let len = lens[i]
    for (let start = 1; start <= 10 - len; start++) {
      let num = start

      for (let n = start + 1; n < start + len; n++) {
        num = 10 * num + n
      }
      if (num <= high && num >= low) {
        res.push(num)
      }
    }
  }

  return res
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions