How can I get the Nth digit of a number from right to left?

6.5k Views Asked by At

How can I get the nth digit of a number when the first digit is on the right-most of the number? I'm doing this on python.

5

There are 5 best solutions below

2
Mureinik On

You could convert the number to a string and then use a negative index to access a specific digit from the end:

>>> num = 123456
>>> n = 3
>>> str(num)[-n]
'4'
3
Thierry Lathuille On

If your numbers are integers, you can compute it with integer division and modulo:

def nth_digit(number, digit):
    return abs(number) // (10**(digit-1)) % 10

nth_digit(4321, 1)
# 1
nth_digit(4321, 2)
# 2

If we go further left, the digit should be 0:

nth_digit(4321, 10)
# 0
1
CodeRocks On

Convert to a string, reverse the string, and then take the index of the string and convert the string back into an integer. This works:

def nth_digit(digit, n):
  digit = str(digit)
  return int(digit[::-1][n])

Let me know if this works for you!

0
Mr. Eivind On

Here's one way, assuming you are talking about integers and the decimal system:

def extract_digit(n, number):

    number = abs(number)

    for x in range(n-1):
        number = number // 10 #integer division, removes the last digit

    return number % 10
0
CodeRocks On

Convert to a string, reverse the string, and then take the index of the string and convert the string back into an integer. This works:

def nth_digit(digit, n):
   digit = str(digit)
   return int(digit[::-1][n])

Let me know if this works for you!