LeetCode400. 第N个数字

https://leetcode-cn.com/problems/nth-digit/
在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …中找到第 n 个数字。
注意:
n 是正数且在32为整形范围内 ( n < 231)。
示例 1:
输入:
3
输出:
3
示例 2:
输入:
11
输出:
0
说明:
第11个数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, … 里是0,它是10的一部分。

思路: 详见该博主
https://blog.csdn.net/qq_28584889/article/details/84894950

int findNthDigit(int n) {
    if(n < 10){
        return n;
    }
    long cur_len = 0;
    long i = 1; // 位数
    long tmp = 0;
    for(i = 1; cur_len < n; i++){
        tmp = 9 * pow(10, i - 1) * i;
        cur_len += tmp;
    }
    i--;
    cur_len -= tmp;
    long front = pow(10 , i - 1) - 1;
    long num = front + (n - cur_len)/i;
    long more = (n - cur_len)%i;
    if(0 == more){
        return num % 10;
    }
    return (int)((num + 1)/(pow(10, i - more)))%10; 
}

猜你喜欢

转载自blog.csdn.net/qq_34595352/article/details/88101714
今日推荐