Nth Digit

来源:互联网 发布:windows中命令Tracert 编辑:程序博客网 时间:2024/06/01 10:03

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 或 10~99 或 100 ~999….),然后确定在这个区间的具体数字,最后确定这个数字的第几位。
注意精度范围!

class Solution {public:    int findNthDigit(int n) {        if(n>=1&&n<=9)            return n;        long start = 1, end = 9, level = 1;        long count = 0 ;        while(count < n){            count += (end - start + 1)*level;            start *= 10;            end = end *10 + 9;            ++level;        }        start/=10;        end = (end - 9 )/10;        --level;        count = count - (end - start + 1)*level;        count = n - count;        int cur = start + count/level-1;        int remain = count % level;        if(remain==0)            return cur%10;        else             ++cur;        int weight = level-remain;        while(weight--)            cur/=10;        return cur%10;    }};
0 0
原创粉丝点击