剑指 Offer 44. 数字序列中某一位的数字

数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。

请写一个函数,求任意第n位对应的数字。

示例 1:

输入:n = 3
输出:3
示例 2:

输入:n = 11
输出:0
 

限制:

0 <= n < 2^31

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

代码:

class Solution {
public:
    int findNthDigit(int n) {
        int num[] = {0,10,90,900,9000,90000,900000,9000000,90000000,238609294};
        int h[] = {0,0,10,100,1000,10000,100000,1000000,10000000,100000000};
        int i = 0;
        while(n >= num[i] * i) {n -= num[i] * i; i ++;}
        int j = h[i] + n / i,k = i - n % i - 1;
        while(k --) j /= 10;
        return j % 10;
    }
};
如果觉得有帮助,点个推荐啦~
原文地址:https://www.cnblogs.com/8023spz/p/13764290.html