400. 第 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 的一部分。

Java
class Solution {
    public int findNthDigit(int n) {
        int level=1;//The level of numbers, we start from one.
        long numbers=9;//The number of current digital levels, we start with a number, there are 9 numbers (1-9), it is a single number

        //Number [1-9] (with 9 digits) is a one-digit number, and the number [10-99] (with 90 digits) is a two-digit number.
        //The number [100-999] (with 900 numbers) is three digits, first we should find what level
        //(I mean which number (one digit, two digits, etc.) the nth digit), once we find the number level,
        //We have already implemented half of the process. If the n-digit * count > 0, it means that the nth bit is not at the current digital level.
        //We should increase the number level to pass more numbers

        while(n-level*numbers>0){
            //Every time we pass numbers at the current number level
            n-=level*numbers;
            level++;
            // The count grows as follows, 9, 90, 900, 9000 ..... because the count may overflow, so I use the long type
            numbers*=10;
        }
        // After the loop, n represents the nth number of the current baseNumber
        //The base is 1, 10, 100, 1000, 10000, etc.
        int baseNumber=(int)Math.pow(10,level-1);
        // find the number where the nth digit is located
        int number=(n-1)/level+baseNumber;
        // Find the number with the nth digit above it
        int mod=(n-1)%level;
        return String.valueOf(number).charAt(mod)-'0';
    }
}

 

 cpp

class Solution {
public:
    int findNthDigit(int n) {
        int level=1;
        long numbers=9;
        while(n-level*numbers>0){
            n-=level*numbers;
            level++;
            numbers*=10;
        }
        int baseNumber=pow(10,level-1);
        int number=(n-1)/level+baseNumber;
        int mod=(n-1)%level;
        return std::to_string(number)[mod]-'0';
    }
};

py

class Solution:
    def findNthDigit(self, n: int) -> int:
        level=1
        numbers=9
        while n-level*numbers>0:
            n-=level*numbers
            level+=1
            numbers*=10
        baseNumber=10**(level-1)
        number=(n-1)/level+baseNumber
        mod=(n-1)%level
        return str(number)[mod]

 

posted @ 2021-02-19 15:59  XXXSANS  阅读(245)  评论(0编辑  收藏  举报