您的位置:首页 > 其它

400. Nth Digit

2018-03-18 11:39 113 查看
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 < 2^31).

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.

找出第N位所在的数字,然后可以把数字转为字符串,这样直接可以访问任何一位。

class Solution {
public:
int findNthDigit(int n) {
long len=1,cnt=9,start=1;
while(n>len*cnt)
{
n -=len*cnt;
cnt *=10;
len++;
start *=10;//记录当前循环区间的第一个数字
}

start +=(n-1)/len;//下标从0开始,所以(n-1)/len即为目标数字在该区间里的坐标
string t=to_string(start);
return t[(n-1)%len]-'0';
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: