[LeetCode] 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.

用暴力搜索 會超時, 所以這是純數學題 數字是有規律的 我們把它分成9個 domain. 每個domain 代表 一位數, 兩位數, 三位數...

#1   1-9
#2   10-99
#3   100-999
#4   1000-9999
#5   10000-99999
#6   100000-999999
#7   1000000-9999999
#8   10000000-99999999
#9   100000000-99999999

這樣就好做了,思路是

1. 先找出 n 是在哪個 domain
2. 再找出 是domain 裡哪一個數, 假設是 whn
3. 最後找出 whn 裡 相對應的 digit


留言