Create 400. Nth Digit.md

This commit is contained in:
唐树森 2018-10-01 11:15:50 +08:00 committed by GitHub
parent b9f7c98a9f
commit 3e6fb6ee7f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

37
400. Nth Digit.md Normal file
View File

@ -0,0 +1,37 @@
# [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;
}
};
```