You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求高效获取序列数字串指定位置字符的方案(支持10亿级位置)

Efficiently Find the Nth Character in the Concatenated Sequence of Natural Numbers

Great question! Generating the entire concatenated string is totally infeasible for huge positions like 1,000,000,000—you'd waste massive amounts of memory and time. Instead, we can use mathematical calculations to directly locate the target character without building the string at all. Here's how to do it efficiently:

Step-by-Step Approach

The key idea is to narrow down which digit-length group the target position falls into, then find the exact number and character within that number:

  • Identify the digit length of the target number
    Start with 1-digit numbers (0-9): these take up 10 characters total. Next, 2-digit numbers (10-99) take 90 numbers × 2 digits = 180 characters. Continue this pattern, subtracting the total characters of each group from your target position until you find the group where the position lies.

  • Find the exact number containing the target character
    Once you know the digit length d, calculate how many full numbers fit into the remaining position. The starting number for d-digit numbers is 10^(d-1) (except for 1-digit numbers, which start at 0). Compute the number as startNumber + Math.floor(offset / d).

  • Find the specific character in that number
    The position within the number is offset % d. Convert the number to a string and pick that index.

JavaScript Implementation

function findNthChar(n) {
    let remaining = n;
    let digitLength = 1;
    let count = 10; // 1-digit numbers: 0-9 (10 total characters)
    let start = 0;

    // Step 1: Locate the digit length group
    while (remaining > count) {
        remaining -= count;
        digitLength++;
        start = Math.pow(10, digitLength - 1);
        count = 9 * start * digitLength;
    }

    // Step 2: Find the exact number holding the target character
    const number = start + Math.floor((remaining - 1) / digitLength);

    // Step 3: Extract the specific character from the number
    const charIndex = (remaining - 1) % digitLength;
    return number.toString()[charIndex];
}

// Test with your example: input 20 should return '4'
console.log(findNthChar(20)); // Output: '4'

// Test with a huge position like 1,000,000,000
console.log(findNthChar(1000000000)); // Runs in milliseconds

Why This Works

This approach runs in O(log₁₀ n) time—for n=1e9, we only need about 9 iterations to narrow down the digit group. There's no string generation or array creation, so it uses minimal memory and completes well within 1 second even for extreme positions.

内容的提问来源于stack exchange,提问作者Mad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:02:48