Nth Digit Problem


Description

LeetCode Problem 400.

Given an integer n, return the n^th digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …].

Example 1:

1
2
Input: n = 3
Output: 3

Example 2:

1
2
3
Input: n = 11
Output: 0
Explanation: The 11^th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.

Constraints:

  • 1 <= n <= 2^31 - 1


Sample C++ Code

First, we calculate how many digits the target number has. For example, if the input is 302, we need to find out the 302th digit belongs to a 3-digit number. This is because for 1-digit numbers, there are 9 of them and they give us 9 digits. For 2-digit numbers, there are 90 of them and they give us 180 digits. For n = 302, 302 - 9 - 90 * 2 = 113, so it belongs to a 3-digit number.

Second, we calculate which number it belongs to. When n = 300, we know it belongs to a 3-digit number, number = 100 + 113 / 3 = 100 + 37 = 137.

Third, we find out which digit in the number it is. When n = 300, we know the digit is in the number 137, and the digit index is 113 % 3 = 2. So the digit is the second one in 137, which is 3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
    int findNthDigit(int n) {
        int base = 9;
        long digits = 1;
        while (n - base * digits > 0) {
            n -= base * digits;
            base *= 10;
            digits++;
        }
        
        int index = (n - 1) % digits;
        int offset = (n - 1) / digits;
        long start = pow(10, digits - 1);
        return to_string(start + offset)[index] - '0';
    }
};




Related Posts

Beautiful Arrangement II Problem

LeetCode 667. Given two integers n and k, construct a...

Range Addition II Problem

LeetCode 598. You are given an m x n matrix...

Perfect Number Problem

LeetCode 507. A perfect number is a positive integer that...

Optimal Division Problem

LeetCode 553. You are given an integer array nums. The...

Minimum Time Difference Problem

LeetCode 539. Given a list of 24-hour clock time points...

Minimum Moves To Equal Array Elements Problem

LeetCode 453. Given an integer array nums of size n,...