1题目
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:
3
Output:
3
Example 2:
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.
2 尝试解
2.1 分析
首先判断第k个字符所在的数字为num,位数为digit_count。一位数共1*9位,两位数共2*90位,三位数共3*900位,由差比数列求和公式,从第一位到第n位数,一共digit_count = ((9n-1)*10^n + 1) / 9位个字符。除去前面所有小于digit_count位数的数字后,得到第k个字符在digit_count位数的数字中相对顺序same_digit_index,进而得到num = 10^(digit_count-1)-1+ceil(same_digit_index/digit_count)。然后得到第k个字符在num中的相对位置。
即先求是几位数,再求所在数字,再求在数字中是第几位。
2.2 代码
class Solution {
public:
int findNthDigit(int n) {
long long sum = 9; //一位数,二位数...i位数长度之和,比如一位数与两位数长度值和是189
int digit_count = 1; //代表digit_count位数
//计算第n个字符所在的数num是几位数,第11个字符0所在的数(10)是两位数
while(n > sum){
digit_count ++;
sum = ((9*digit_count-1)*pow(10,digit_count)+1)/9;
}
int same_digit_index = n-((9*(digit_count-1)-1)*pow(10,digit_count-1)+1)/9; //计算该字符在n位数的相对位置,起始值,两位数的起始值是10,三位数的起始值是190
int num_index = ceil(double(same_digit_index) / (digit_count));//在digit_count位数中,num是第几个,在两位数中,10是第1个
int num = pow(10,digit_count-1)+ num_index -1;//进而得出num的值
int num_digit_index = (same_digit_index)-digit_count*(num_index-1);
int result = num/pow(10,digit_count-num_digit_index);
result = result % 10;
return result;
}
};
3 标准解
class Solution
{
// date: 2016-09-18 location: Vista Del Lago III Apartments
public:
int findNthDigit(int n)
{
// step 1. calculate how many digits the number has.
long base = 9, digits = 1;
while (n - base * digits > 0)
{
n -= base * digits;
base *= 10;
digits ++;
}
// step 2. calculate what the number is.
int index = n % digits;
if (index == 0)
index = digits;
long num = 1;
for (int i = 1; i < digits; i ++)
num *= 10;
num += (index == digits) ? n / digits - 1 : n / digits;;
// step 3. find out which digit in the number is we wanted.
for (int i = index; i < digits; i ++)
num /= 10;
return num % 10;
}
};