问题描述
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:
3Output:
3
Example 2:
Input:
11Output:
0Explanation:
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.
思路分析
找到一连串的1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …的第n个数字。
真的是easy题么,好难啊。完全不会的。
首先确定这是一个几位数,有9个一位数,90个两位数,900个三位数……所以用n循环减去9,2*90,3*900……就可以得到它是几位数。
然后用这时的(n-1)%digits + 1得到这个第n个数字是这个数的第几位。
再确定这个数是多少,首先先制造一个digits位数,然后再加上n/digits或者n/digits - 1(当这个数字是数的最后一位的时候,要往前回一个数。否则算出来的是下一个数了。)
最后再辗转处10将这个数字降到最后一位,模10返回。
代码
class Solution {
public:
int findNthDigit(int n) {
//find the number of the digits
long digits = 1, base = 9;
while (n - digits*base > 0){
n = n - digits*base;
digits++;
base *= 10;
}
//find the index of the nth in the num
int index = (n - 1) % digits + 1;
//find the num
long num = 1;
for (int i = 1; i < digits; i++){
num *= 10;
}
if (index == digits)
num += n/digits - 1;
else
num += n/digits;
//return the nth
for (int i = index; i < digits; i++){
num /= 10;
}
return num % 10;
}
};
时间复杂度:
未知
空间复杂度:
O(1)
反思
太难了……数学题啊……