Skip to content
Advertisement

How to extract digits from a number from left to right?

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement