[leetcode] 400. Nth Digit

时间:2021-06-14 03:48:38

https://leetcode.com/contest/5/problems/nth-digit/

刚开始看不懂题意,后来才理解是这个序列连起来的,看一下第几位是几。然后就是数,1位数几个,2位数几个,3位数几个,int范围2e10,所以处理到11位数差不多,仔细算一下可以更少,然后先找到是几位数,然后除以位数,找到这个数是多少,取余看是第几位,然后就可以了。我预处理每位的个数和开始的位置。

 class Solution {
public:
long long d[];
int b[];
int init(int n) {
d[] = ;
d[] = ;
b[] = ;
for (int i = ; i < ; i++) {
d[i] = d[i - ] * ;
b[i] = b[i - ] * ;
}
for (int i = ; i < ; i++) {
d[i] = d[i] * i;
// cout << d[i] << endl;
}
int i = ;
for (i = ; i < ; i++) {
if(d[i] < n)
n -= d[i];
else break;
}
n--;
int t1 = n / i, t2 = n % i;
int k = b[i] + t1;
stringstream ss; string s1;
ss << k; s1 = ss.str();
//cout << t1 << " asd " << t2 << endl;
//cout << s1 << endl;
//reverse(s1.begin(), s1.end());
return s1[t2] - ''; }
int findNthDigit(int n) {
return init(n);
}
};