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.
class Solution {
public:
int findNthDigit(int n) {
if(n<=0)
return -1;
int index = n;
int digits = 1;
while(true)
{
long numbers =countOfIntegers(digits);
if(index<numbers*digits)
return digitAtIndex(index, digits);
index -= digits*numbers;
digits++;
}
return -1;
}
private:
long countOfIntegers(int digits)
{
if(digits == 1)
return 10;
int count = (int)std::pow(10, digits-1);
return 9*count;
}
int digitAtIndex(int index, int digits)
{
int number = beginNumber(digits) + index/digits;
int indexFromRight = digits - index%digits;
for(int i=1; i<indexFromRight; ++i)
number/=10;
return number%10;
}
int beginNumber(int digits)
{
if(digits == 1)
return 0;
return (int)std::pow(10, digits-1);
}
};
本文介绍了一个算法问题,即如何找到无限整数序列1,2,3,4,5,6...中的第N位数字。通过递进的方式,文章详细解释了如何判断目标数字位于哪个长度级别的数字区间,并提供了具体的实现代码。
1021

被折叠的 条评论
为什么被折叠?



