寻求高效获取序列数字串指定位置字符的方案(支持10亿级位置)
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 lengthd, calculate how many full numbers fit into the remaining position. The starting number ford-digit numbers is10^(d-1)(except for 1-digit numbers, which start at 0). Compute the number asstartNumber + Math.floor(offset / d).Find the specific character in that number
The position within the number isoffset % 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

