Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

400. 第N个数字 #254

Merged
merged 5 commits into from
Apr 13, 2020
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions solution/0400-0499/0400.Nth Digit/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution {
public int findNthDigit(int n) {
/***
* 12345678910111213
* 规律个位数9个数一共有9*1,两位数90个数 一共有90*2个数字,三位数有900个数一共有900*3个数字,以此类推
* 举例15,15-9=6,6/2=3...0,余数是0,那么这个数值value=10*(2-1)+(3-1)=12,整除取最后一位 12%10=2
* 举例14,14-9=5,5/2=2...1,余数不为0,那么这个数值value=10*(2-1)+2=12,则为这个数的第余数个 12/(10*(2-1))%10=1
*/
long max=9;
long num=n;
long digits=1;
while (n>0) {
if(num-max*digits>0) {
num=num-max*digits;
digits++;
max=max*10;
}else {
long count=num/digits;
long childDigits=num%digits;
long value=(long)Math.pow(10,digits-1)+count-1;
if (childDigits == 0) {
return (int) (((long) Math.pow(10, digits - 1) + count - 1) % 10);
} else {
return (int) (((long) Math.pow(10, digits - 1) + count) / ((long) Math.pow(10, (digits - childDigits))) % 10);
}
}
}
return 0;

}
}