Leetcode400Nth Digit第N个数字

在无限的整数序列 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的一部分。

class Solution {
public:
    int findNthDigit(int n) {
        long long digit = 1; //当前一个数有几位数
        long long start = 1; //当前从哪个数开始
        long long total = 9; //当前digit位数的数有多少个
        while(n > digit * total)
        {
            n -= total * digit;
            digit += 1;
            start *= 10;
            total *= 10;
        }

        int number = start + (n - 1) / digit; //以输入11为例子 2 / 2 == 1 但是第二位在10上,而不是在start + 2 / 2 == 11上,所以n - 1
        string str = to_string(number);
        int res = str[(n - 1) % digit] - '0';//下标从0开始所以n - 1
        return res;
    }
};
原文地址:https://www.cnblogs.com/lMonster81/p/10434098.html