Nth Digit

medium math binary search

Problem

Consider the infinite string formed by concatenating positive integers: "123456789101112…". Return the n-th digit (1-indexed).

Inputn = 11
Output0
After skipping 9 single-digit numbers we have 2 digits left in the 2-digit band → land in "10" at offset 1 → '0'.

def find_nth_digit(n):
    digits, count, start = 1, 9, 1
    while n > digits * count:
        n -= digits * count
        digits += 1
        count *= 10
        start *= 10
    num = start + (n - 1) // digits
    offset = (n - 1) % digits
    return int(str(num)[offset])
function findNthDigit(n) {
  let digits = 1, count = 9, start = 1;
  while (n > digits * count) {
    n -= digits * count;
    digits++;
    count *= 10;
    start *= 10;
  }
  const num = start + Math.floor((n - 1) / digits);
  const offset = (n - 1) % digits;
  return parseInt(String(num)[offset], 10);
}
class Solution {
    public int findNthDigit(int n) {
        long digits = 1, count = 9, start = 1;
        while (n > digits * count) {
            n -= digits * count;
            digits++;
            count *= 10;
            start *= 10;
        }
        long num = start + (n - 1) / digits;
        int offset = (int)((n - 1) % digits);
        return Long.toString(num).charAt(offset) - '0';
    }
}
int findNthDigit(int n) {
    long long digits = 1, count = 9, start = 1;
    while (n > digits * count) {
        n -= digits * count;
        digits++;
        count *= 10;
        start *= 10;
    }
    long long num = start + (n - 1) / digits;
    int offset = (n - 1) % digits;
    return to_string(num)[offset] - '0';
}
Time: O(log n) Space: O(1)