JSFiddle - React, Tailwind, and code Playground
by Mike Lin
JavaScript
function getNodeCount(rootValue, n) {
let base = 10n
let count = 1n
while (BigInt(rootValue) * BigInt(base) <= BigInt(n)) {
// 如果本层级的最大数小于n, 那么节点数并不终结在本层级下,所以个数可以加上本层级的全部节点数
if (((BigInt(rootValue) + 1n) * BigInt(base)) - 1n < BigInt(n)) {
count = BigInt(count) + BigInt(base)
} else {
count = BigInt(count) + BigInt(n) + 1n - BigInt(rootValue) * BigInt(base)
}
base = BigInt(base) * 10n
}
return count
}
function lexicalOrder(n, m) {
let ans = 1
while(m !== 0) {
const count = getNodeCount(ans, n)
console.log(count, m, ans)
if (BigInt(count) >= BigInt(m)) {
m = BigInt(m) - 1n
if (BigInt(m) === 0n) {
return ans
}
ans = BigInt(ans) * 10n
} else {
m = BigInt(m) - BigInt(count)
ans = BigInt(ans) + 1n
}
}
}
const m = 5555555555555555n
console.log(`字典序排在第${m}是:`, lexicalOrder(10000000000000000n, m))