GuilinDev

Lc0400

05 August 2008

400. Nth Digit

给一个整数 n ,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …] 中找出并返回第 n 位上的数字。 Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {

    public int findNthDigit(int n) {

        if (n < 10) return n;

        //number of total digits possible in the current interval of powers of 10
        double lastBaseDCountTotal = 9;
        double lastBase = 10;
        //number of total digits possible in the previous interval of powers of 10
        double prevBaseDCountTotal = 0;
        //number of digits in a number in the current interval ( e.g. numbers between 10 and 100 have 2 digits)
        double digitCount = 1;

        //Find the interval of powers of 10 where Nth digit lives by looking at number of total digits
        while (n > lastBaseDCountTotal) {
            digitCount++;
            prevBaseDCountTotal = lastBaseDCountTotal;
            lastBaseDCountTotal += 9 * digitCount * lastBase;
            lastBase *= 10;
        }

        //then we find how many digits we need after subtracting the total number of digits in the previous interval 
        //and calculate how many numbers we need in the new interval to make up for the difference
        double remainingCount = n - prevBaseDCountTotal;
        int whereItsAt = (int) ((lastBase / 10 - 1d) + Math.ceil(remainingCount / digitCount));

        //after this, we need to find which character of the number it is
        //we need to look at the remainder of the division operation so we use modulus
        double mod = remainingCount % digitCount;
        int whichChar = (int) ((mod == 0 ? digitCount : mod) - 1d);
        return Character.getNumericValue(String.valueOf(whereItsAt).charAt(whichChar));
    }
}