Infinite Sequence Nth Digit
Find the Nth digit in the infinite sequence formed by concatenating positive integers starting from 1.
Understand the Problem
Problem Statement
Given a positive integer N, find and print the Nth digit in the infinite sequence formed by concatenating all positive integers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ... and so on.
For example, the sequence begins as: 1234567891011121314151617181920212223...
The 5th digit is 5, and the 11th digit is 0 (from the number 10).
Constraints
- 1 ≤ N ≤ 10^9
- N is a positive integer
- The sequence starts from 1 and goes to infinity
Examples
55The infinite sequence starts as 123456789101112... The 5th digit is 5, which comes from the single digit number 5.
110The sequence is 123456789101112... The first 9 digits are from numbers 1-9. The 10th and 11th digits come from the number 10. Specifically, the 10th digit is 1 and the 11th digit is 0.
152The sequence is 123456789101112131415... The 15th digit is 2, which comes from the number 12 (specifically the second digit of 12).
Solution
#include <stdio.h>
#include <math.h>
int findNthDigit(int n) {
long long digits = 1;
long long count = 9;
long long start = 1;
// Find the digit group (1-digit, 2-digit, etc.)
while (n > digits * count) {
n -= digits * count;
digits++;
count *= 10;
start *= 10;
}
// Find the specific number
start += (n - 1) / digits;
// Find the specific digit in that number
char numberStr[20];
sprintf(numberStr, "%lld", start);
return numberStr[(n - 1) % digits] - '0';
}
int main() {
int n;
scanf("%d", &n);
printf("%d\n", findNthDigit(n));
return 0;
}The C solution implements the mathematical approach:
- Initialize variables to track digit length (digits), count of numbers in current group (count), and starting number of current group (start).
- Loop to find which digit group contains position N by subtracting the total digits from previous groups.
- Calculate the specific number that contains the Nth digit using integer division.
- Convert the number to string and extract the specific digit using modulo arithmetic.
- Return the digit as an integer by subtracting ASCII '0'.