leetcode 400 Add to List 400. Nth Digit

时间:2023-03-09 17:42:54
leetcode 400  Add to List 400. Nth Digit

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.

这道题目我之前见过。。。。一开始用下边注释的代码写,也通过了不过有点费时。后来改成取模。

class Solution {
public:
int findNthDigit(int n) {
// 2: 90 3:900 4: 9000 5:90000 6: 900000 7:9000000 8:90000000 9:900000000 10:9000000000
long x = ;
long t = ;
if (n < ) return n;
while (n > x * t) {
n -= x * t;
x++;
t *= ;
}
long sum = ;
int m = n % x;
if (m == ) return ((long)pow(10.0,x-) + n/x - )%;
else {
long q = (pow(10.0, x-) + (n/x) );
for (int j = ; j < x - m; ++j) q/=;
return q%;
}
/*
for (int i = 0; i < t; ++i) {
sum += x;
if (sum == n) {
return (i % 10);
}
else if (sum > n) {
long y = sum - n;
long z = pow(10.0,(x - 1)) + i;
cout <<z;
for (int j = 0; j < y; ++j) {
z /= 10;
}
return z%10;
}
}
*/
}
};