Leetcode

Nth Digit

  • Time:O(\log n)
  • Space:O(1)

C++

class Solution {
 public:
  int findNthDigit(int n) {
    int digitSize = 1;
    int startNum = 1;
    long count = 9;

    while (digitSize * count < n) {
      n -= digitSize * count;
      ++digitSize;
      startNum *= 10;
      count *= 10;
    }

    const int targetNum = startNum + (n - 1) / digitSize;
    const int index = (n - 1) % digitSize;
    return to_string(targetNum)[index] - '0';
  }
};

JAVA

class Solution {
  public int findNthDigit(int n) {
    int digitSize = 1;
    int startNum = 1;
    long count = 9;

    while (digitSize * count < n) {
      n -= digitSize * count;
      ++digitSize;
      startNum *= 10;
      count *= 10;
    }

    final int targetNum = startNum + (n - 1) / digitSize;
    final int index = (n - 1) % digitSize;
    return String.valueOf(targetNum).charAt(index) - '0';
  }
}

Python

class Solution:
  def findNthDigit(self, n: int) -> int:
    def getDigit(num: int, pos: int, digitSize: int):
      if pos == 0:
        return num % 10
      for _ in range(digitSize - pos):
        num //= 10
      return num % 10

    digitSize = 1
    startNum = 1
    count = 9

    while digitSize * count < n:
      n -= digitSize * count
      digitSize += 1
      startNum *= 10
      count *= 10

    targetNum = startNum + (n - 1) // digitSize
    pos = n % digitSize

    return getDigit(targetNum, pos, digitSize)