## The Problem:

Given an integer, find its `k`

digit.^{th}

**Example**

For `n = 578943`

and `k = 2`

, the output should be

`kthDigit(n, k) = 7`

.

**Input/Output**

**[time limit] 4000ms (py)**

**[input] integer n***Constraints:*

`10`

.^{5}≤ n ≤ 10^{6}**[input] integer k**A non-negative integer.*Constraints:*

`1 ≤ k ≤ 7`

.**[output] integer**`k`

digit of the given number or^{th}`-1`

there are less than k digits.

## The Solution:

`def kthDigit(n, k):`

if (len(str(n))<k):

return -1

return int(str(n)[k-1])

## The Explanation:

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.

Advertisements