0

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
hacq
  • 21
  • 2
  • 3
  • Can you post some code of what you have tried so far? Do you have some example inputs / outputs? – Cameron Downer Aug 28 '18 at 15:58
  • Let's say the number is 1234.567. What is its 4th digit? Or is the number guaranteed to be an integer? – Kevin Aug 28 '18 at 15:58
  • 1
    You can get the logic from [here](https://stackoverflow.com/questions/39644638/how-to-take-the-nth-digit-of-a-number-in-python) which is about nth digit from left. You can modify the same for your case. – dodobhoot Aug 28 '18 at 16:04
  • Although the duplicate is asking how to count from the left rather than the right, the second answer is actually counting from the right, and the accepted one can count from either side (it’s just a matter of negative indexing), so I think your best answers are all there. – abarnert Aug 28 '18 at 16:14

5 Answers5

2

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'
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

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
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
0

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
Mr. Eivind
  • 199
  • 2
  • 11
0

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!

CodeRocks
  • 655
  • 5
  • 10
  • 25
-2

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!

CodeRocks
  • 655
  • 5
  • 10
  • 25