您的位置:首页 > 其它

LeetCode-400. Nth Digit

2017-02-22 11:03 246 查看
问题:https://leetcode.com/problems/nth-digit/?tab=Description

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,

**分析:**S1=1 S2=12 S3=123 S4=1234 … S9=123456789 S10=12345678910

S11=1234567891011 … 求在S串中的第N个数字是多少。

一位数有9个,两位数有90个,三位数有900个。。。所以对于给定的一个数,先看它落在几位数的范围内,再找到具体落在哪个数字上,落在哪个数字的哪一位上。例如n=140,因为一位数有9个,可以位数加1,n-9=131。两位有90个,2*90=180>131,所以目标数字是两位的。10+(131-1)/2=75,落在75上。(131-1)%2=0,落在75的第0位,即7。如此得到。

C++代码:

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';
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode math