400. Nth Digit

QUESTION:

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.

EXPLANATION:

题目的意思是:1,2,3,4.。。第11个数是什么?9后面是10,但是10由1和0组成, 第10个数是1,第11个数就是0了。

思路是:

1.首先需要算出是几位数。1位数是1-9,2位数是10-99.3位数就是100-999.在算这个的同时保存住上一个关键节点,比如1是9,2就是2*90+9,3就是3*900+2*90+9.

2.算出距离关键节点偏移了多少。

3.偏移的值除以几位数,就可以获取到具体的数了。

4.再算出第几位就可以了,取模就是具体的个位还是十位了。

SOLUTION:

public class Solution {
    public int findNthDigit(int n) {
        if (n <= 9) return n;
        int sum = 0, index = 0, tmp = sum; double base = 0;
        while (sum < n) {
            index++;
            tmp = sum;
            base = Math.pow(10, index - 1);
            sum += 9 * base * index;
        }
        int delta = (n - tmp - 1) / index;
        int carry = (n - tmp - 1) % index;
        int num = (int) (base + delta);
        return (num + "").charAt(carry) - '0';
    }
}