leetcode [#400]

目录

题目

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …

Example1:
Input:
3

Output:
3

Example2:
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.

Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).


解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Solution {
public int findNthDigit(int n) {
int k = 0;
int temp = n;
while(temp > 9 * Math.pow(10, k) * (k + 1)){
temp = temp - 9 * (int)Math.pow(10, k) * (k + 1);
k++;
}
int result = 0;
int division = temp / (k+1);
if(n <= 9){
result = n;
} else {
int mode = temp % (k+1);
if(mode != 0){
int curr = (int)Math.pow(10, k) + division;
int p = curr;
int[] digitArr = new int[k+1];
int m = k;
while(p > 0){
digitArr[m] = p % 10;
p = p / 10;
m--;
}
result = digitArr[mode - 1];
} else {
int curr = (int)Math.pow(10, k) + division - 1;
result = curr % 10;
}
}
return result;
}
}

注意事项

  1. 是一道数学规律题目。给出从1开始递增1的无限整数序列。要求返回第n位的数字。这个数字可能是整数序列中某个数的某一位。
  2. 主要规律如下:
    从1开始的整数:

    位数为1的: 1 ~9 , 共9 个;
    位数为2的: 10 ~99, 共99个;
    位数为3的: 100 ~999 ,共999个;
    位数为4的: 1000~9999,共9999个;
    … …

  3. 根据如上规律对所有数字进行分组,也就是位数相同的整数在一组。给定一个数,先通过while循环判断在哪个组里。之后在这个组中,判断它属于哪个数字。