Skip to content

Commit 5f6ca51

Browse files
committedApr 11, 2020
add Nth Digit
1 parent be31a57 commit 5f6ca51

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public int findNthDigit(int n) {
3+
/***
4+
* 12345678910111213
5+
* 规律个位数9个数一共有9*1,两位数90个数 一共有90*2个数字,三位数有900个数一共有900*3个数字,以此类推
6+
* 举例15,15-9=6,6/2=3...0,余数是0,那么这个数值value=10*(2-1)+(3-1)=12,整除取最后一位 12%10=2
7+
* 举例14,14-9=5,5/2=2...1,余数不为0,那么这个数值value=10*(2-1)+2=12,则为这个数的第余数个 12/(10*(2-1))%10=1
8+
*/
9+
long max = 9;
10+
long num = n;
11+
long digits = 1;//是几位数
12+
while (n > 0) {
13+
if (num - max * size > 0) {
14+
num = num - max * size;
15+
digits++;
16+
max = max * 10;
17+
} else {
18+
long count = num / digits;
19+
long childDigits = num % digits;
20+
if (childDigits == 0) {
21+
return (int) (((long) Math.pow(10, digits - 1) + count - 1) % 10);
22+
} else {
23+
return (int) (((long) Math.pow(10, digits - 1) + count) / ((long) Math.pow(10, (digits - childDigits))) % 10);
24+
}
25+
}
26+
}
27+
return 0;
28+
29+
}
30+
}

0 commit comments

Comments
 (0)
Please sign in to comment.