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

Three Equal Parts Problem

LeetCode 927. You are given an array arr which consists...

Surface Area Of 3D Shapes Problem

LeetCode 892. You are given an n x n grid...

Super Palindromes Problem

LeetCode 906. Let’s say a positive integer is a super-palindrome...

Smallest Range I Problem

LeetCode 908. You are given an integer array nums and...

Projection Area Of 3D Shapes Problem

LeetCode 883. You are given an n x n grid...

Prime Palindrome Problem

LeetCode 866. Given an integer n, return the smallest prime...