400. Nth Digit

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...

Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).

 

Example 1:

Input:
3

Output:
3

 

Example 2:

Input:
11

Output:
0

Explanation:
The 11th 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.

 

Approach #1: Math. [Java]

class Solution {
    public int findNthDigit(int n) {
        int len = 1;
        int start = 1;
        long count = 9;
        
        while (n > len * count) {
            n -= len * count;
            len++;
            start *= 10;
            count *= 10;
        }
        
        int num = start + (n - 1) / len;
        String s = Integer.toString(num);
        return Character.getNumericValue(s.charAt((n-1) % len));
    }
}

  

Analysis:

Straight forward way to solve the problem in 3 steps:

1. find the length of the number where the nth digit is from.

2. find the actual number where the nth digit is from

3. find the nth digit and return.

 

The reason why we reduce 1 from n is to calibrate the difference between rank and natural number.

We initialize 'start' as 1, which is the 1st element in the sequence. It is the same as an array, where the index should be now 0-based. Actually, we can subtract 1 from n at the very beginning.

 

Reference:

https://leetcode.com/problems/nth-digit/discuss/88363/Java-solution

 

posted @ 2019-05-05 21:14  Veritas_des_Liberty  阅读(274)  评论(0编辑  收藏  举报