How to Find k-th digit of a number?

The Problem:

Given an integer, find its kth digit.

Example

For n = 578943 and k = 2, the output should be
kthDigit(n, k) = 7.

Input/Output

  • [time limit] 4000ms (py)
  • [input] integer nConstraints:
    105 ≤ n ≤ 106.
  • [input] integer kA non-negative integer.

    Constraints:
    1 ≤ k ≤ 7.

  • [output] integerkth digit of the given number or -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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s