Skip to content

Latest commit

 

History

History
109 lines (81 loc) · 2.27 KB

File metadata and controls

109 lines (81 loc) · 2.27 KB

English Version

题目描述

给你一个整数 n ,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] 中找出并返回第 n 位上的数字。

 

示例 1:

输入:n = 3
输出:3

示例 2:

输入:n = 11
输出:0
解释:第 11 位数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是 0 ,它是 10 的一部分。

 

提示:

  • 1 <= n <= 231 - 1

解法

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';
    }
};

...