Skip to content

Latest commit

 

History

History

0400.Nth Digit

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

English Version

题目描述

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

解法

Python3

class Solution:
    def findNthDigit(self, n: int) -> int:
        bits, t = 1, 9
        while n > bits * t:
            n -= bits * t
            bits += 1
            t *= 10

        start = 10 ** (bits - 1) + (n // bits) - 1
        if n % bits == 0:
            return start % 10
        return int(str((start + 1))[(n % bits) - 1])

Java

class Solution {
    public int findNthDigit(int n) {
        int bits = 1, t = 9;
        while (n / bits > t) {
            n -= bits * t;
            ++bits;
            t *= 10;
        }
        int start = (int) Math.pow(10, bits - 1) + (n / bits) - 1;
        if (n % bits == 0) {
            return start % 10;
        }
        return String.valueOf(start + 1).charAt((n % bits) - 1) - '0';
    }
}

C++

class Solution {
public:
    int findNthDigit(int n) {
        int bits = 1, t = 9;
        while (n / bits > t)
        {
            n -= bits * t;
            ++bits;
            t *= 10;
        }
        int start = pow(10, bits - 1) + (n / bits) - 1;
        if (n % bits == 0) return start % 10;
        return to_string(start + 1)[(n % bits) - 1] - '0';
    }
};

...