题目链接:https://leetcode.com/problems/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.
分析:
1.1位数共有9=9·1个, 1~9;
2.2位数共有90=9·10个, 10~99;
3.3位数共有900=9·10·10个, 100~999;
class Solution {
public:
int findNthDigit(int n) {
int len = 1, base = 1; // len表示当前数的位数, base表示当前位是个位、百位、千位等...
while (n > 9L * base * len) {
n -= 9 * base * len;
len++;
base *= 10;
}
// curNum是含有所找digit的那个数
// n-1原因是,base比多了一位
int curNum = (n - 1)/len + base, digit = 0;
for (int i = (n - 1) % len; i < len; ++i) { // 根据偏移量找到所找的数字
digit = curNum % 10;
curNum /= 10;
}
return digit;
}
};
class Solution{
public:
int findNthDigit(int n)
{
long digit=1,ith=1,base=9;
while(n>base*digit)
{
n-=base*(digit++);
ith+=base;
base*=10;
}
return to_string(ith+(n-1)/digit)[(n-1)%digit]-'0';
}
};