1,题目要求
Find the n-th 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 < 2^31).
找出一系列数字按顺序排列之后的的第n位的值。
2,题目思路
不同位数有着不同的长度情况,因此,整个问题可以分成三个步骤来做。
1,找出给定位数的数字,其数字位数是多少(0-9?10-99?100-999?… )
2,利用位数情况,确定该数字。
3,利用偏移量,确定对应位数。
3,程序源码
class Solution {
public:
int findNthDigit(int n) {
int len = 1;//记录当前数字是几位数
long count = 9;
long starter = 1;//记录开始位置
while(n - len*count>0){
n = n -len*count;
len++;
count = count*10;
starter = starter*10;
}
string res = to_string(starter + (n-1)/len);//因为starter中已经占有了len位长度了,因此n-1
return res[(n-1)%len] - '0';
}
};