Given an integer, find its
n = 578943 and
k = 2, the output should be
kthDigit(n, k) = 7.
- [time limit] 4000ms (py)
- [input] integer nConstraints:
105 ≤ n ≤ 106.
- [input] integer kA non-negative integer.
1 ≤ k ≤ 7.
- [output] integer
kthdigit of the given number or
-1there are less than k digits.
def kthDigit(n, k):
Probably the easiest way to do it is to convert the number into string. Here in the first line, we convert the number n to string and check its length. If it is shorter than k, then we don’t have that many digits in the number. So, we return -1.
Otherwise, now we have a string and its k-th char is the number we are looking for. (0-based, so, we need to get k-1.) Because we have a char, we need to convert it back to int and then return.