Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

math

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?

like image 728
Borol Avatar asked Dec 25 '16 13:12

Borol


People also ask

How do you extract digits from a number?

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.

How do I extract all digits from a string?

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.


1 Answers

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
like image 84
AlokThakur Avatar answered Sep 19 '22 22:09

AlokThakur