File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 400 Nth Digit
2
+
3
+ #### Description
4
+
5
+ [ link] ( https://leetcode.com/problems/nth-digit/ )
6
+
7
+ ---
8
+
9
+ #### Solution
10
+
11
+ observation: 假设我们要找第2886 个位 (就target数 是998,target bit 是8)
12
+
13
+ - 2886 - 9 - 9 * 10 * 2 = 2697 < 9* 10* 10* 3 = 2700
14
+ - target 就落在了区域3中( 100- 999 ),因为这个区域中每一位都有3位,所以可以计算target
15
+ - target 数是以 100 为起始数,(2697 - 1)/3 = 898 为100以后的数,-1是因为起始数本来就算一个数,不能重复计算
16
+ - target 数 = 100 + 898 = 998
17
+ - (2697-1) % 3 = 2 就是 998 的target bit
18
+ - target bit = 998.charAt( 2 ) = 8;
19
+
20
+ ---
21
+
22
+ #### Code
23
+
24
+ <!-- O(n) -->
25
+
26
+ ``` python
27
+ class Solution :
28
+ def findNthDigit (self , n : int ) -> int :
29
+ start = 1
30
+ base = 9
31
+ digits = 1
32
+
33
+ # step 1 find how many digits the number need
34
+ while n > base * digits:
35
+ n -= base * digits
36
+ digits += 1
37
+ base *= 10
38
+ start *= 10
39
+
40
+ # step 2 find what number we need
41
+ target = start + (n - 1 ) // digits
42
+ reminder = (n - 1 ) % digits
43
+
44
+ # step 3 find which digit we need
45
+ return int (str (target)[reminder])
46
+ ```
You can’t perform that action at this time.
0 commit comments