LeetCode/solutions/400. Nth Digit.md

38 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [400. Nth Digit](https://leetcode.com/problems/nth-digit/description/)
# 思路
计算序列1、2、3、4、5、6、7、8、9、10、11...中第n个数字(digit注意不是数)是什么。
我们可以将这个序列分成很多类:
* 第一类1、2、3...9共9(设为base下同)个数, 即每个数只包含1(设为k下同)个数字一共有base * k = 9 个数字;
* 第二类10、11、12...99base = 90k = 2;
* 第三类100、101、102...999,base = 900k = 3;
* ......
设所求的digit落在数target上则我们可根据上述规律算出target具体是多少然后再算出所求具体是target的哪一个digit。
注意:
当我们算base * k 的时候结果可能超过int的表示范围所以要定义成long long型。
# C++
```
class Solution {
public:
int findNthDigit(int n) {
if(n < 10) return n;
// 计算target
long long base = 9, k = 1;
while(n > base * k){
n -= base * k;
base *= 10;
k++;
}
int target = base / 9 + (n - 1) / k;
// 计算所求digit具体是target的哪一位
while(n % k != 0) {
target /= 10;
n++;
}
return target % 10;
}
};
```