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