Skip to content

400. Nth Digit 👎

  • Time: $O(\log n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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';
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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';
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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)