您的位置:首页 > 其它

400. Nth Digit

2016-09-21 12:52 92 查看
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-9,9个,两位数从10-99,90个,三位数从100-999,900个,以此类推,我们要做的就是将n定位在一个几位数的区间里,然后算一下和这个区间的头或者尾的差距从而定位具体的数字。思路很简单,可能会有的错误就是虽然n是int,但我们算的数字总和可能会溢出,所以这里使用long long int来做。

代码如下:

int findNthDigit(int n) {
long long int st = 9;
long long int bits = 1;
long long int sum = 0;
while (true) {
sum += (st * bits);
if (sum >= n) break;
st = st * 10;
bits++;
}

int pos = pow(10.0, double(bits)) - 1 - (sum - n)/(bits);
int rem = sum - n - bits * ((sum - n) / bits);
int temp = pow(10.0, double(rem));

return (pos / temp) % 10;
}


注意c++里的pow求次方的函数操作类型是double。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: