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.
How can I get the Nth digit of a number from right to left?
6.5k Views Asked by hacq At
5
There are 5 best solutions below
3
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
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!
You could convert the number to a string and then use a negative index to access a specific digit from the end: