剑指 Offer 44. 数字序列中某一位的数字
方法:找规律
解题思路
- 找第\(n\)位对应的数为几位数;
- 找该数的具体值;
- 找第\(n\)位在该数中的第几位。

代码
class Solution {
public:
int findNthDigit(int n) {
int digit = 1;
long long start = 1, count = 9;
while (count < n) { // 1
n -= count;
start *= 10;
digit ++ ;
count = 9 * start * digit;
}
int num = start + (n - 1) / digit; // 2
string s = to_string(num);
return s[(n - 1) % digit] - '0'; // 3
}
};
复杂度分析
时间复杂度:\(O(logn)\);
空间复杂度:\(O(1)\)。

浙公网安备 33010602011771号