Given an integer n
, return the nth
digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]
.
Example 1:
Input: n = 3 Output: 3
Example 2:
Input: n = 11 Output: 0 Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
Constraints:
1 <= n <= 231 - 1
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])
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';
}
}
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';
}
};