
我们通过找规律可以发现,当位数为xxx时,其占用的位数为x×9×10x−1x\times9\times10^{x-1}x×9×10x−1。因此我们可以不断循环并增大位数xxx直至n−x 具体思路同上,区别在于我们可以通过范围确定位数不超过9,从而使用二分查找来直接进行查询。class Solution {
public:int findNthDigit(int n) {int d = 1, count = 9;while (n > (long) d * count) {n -= d * count;d++;count *= 10; }int index = n - 1;int start = (int) pow(10, d - 1);int num = start + index / d;int digitIndex = index % d;int digit = (num / (int) (pow(10, d - digitIndex - 1))) % 10;return digit;}
};
2、二分查找
class Solution {
public:int findNthDigit(int n) {int low = 1, high = 9;while (low < high) {int mid = (high - low) / 2 + low;if (totalDigits(mid) < n) {low = mid + 1;} else {high = mid;}}int d = low;int prevDigits = totalDigits(d - 1);int index = n - prevDigits - 1;int start = (int) pow(10, d - 1);int num = start + index / d;int digitIndex = index % d;int digit = (num / (int) (pow(10, d - digitIndex - 1))) % 10;return digit;}int totalDigits(int length) {int digits = 0;int curLength = 1, curCount = 9;while (curLength <= length) {digits += curLength * curCount;curLength++;curCount *= 10;}return digits;}
};
上一篇:把你的话转过来,回到我的父亲那里
下一篇:你的话在听,你的话在辩