Leetcode - Nth Digit

My code:

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

reference:
https://discuss.leetcode.com/topic/59314/java-solution

这道题目没能自己做出来。虽然是easy,但感觉挺难的。

上面的分析写的不错。

首先,我们先要确定,n的长度

1-9 10-99 100-999 1000-9999
10 90 900 9000

以此类推,算出 n 所在的范围,同时记录下,这个范围的开头那个数字。

此时的 n 就是这段区域内的偏移量 offset
我们还需要把它转换成 index
index = n - 1

然后他代表的数字就是 start += index / 2;

最后我们根据 index 和 len,算出他在这个数字中的 offset = index % len

Anyway, Good luck, Richardo! -- 09/23/2016

你可能感兴趣的:(Leetcode - Nth Digit)