I know that I can extract digits from a number from right to left by implementing something like:
while (number => 10)
digit = number modulo 10
number = number / 10
But is there a way to do it from left to right that works similar to this one, simply by using stuff like the modulo value?
Extracting digits of a number is very simple. When you divide a number by 10, the remainder is the digit in the unit's place. You got your digit, now if you perform integer division on the number by 10, it will truncate the number by removing the digit you just extracted.
This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.
If you don't have problem with recursion approach then here is a solution with little change in your code:-
def get_digit(num):
if num < 10:
print(num)
else:
get_digit(num // 10)
print(num % 10)
Usage
>>> get_digit(543267)
5
4
3
2
6
7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With