Get all digits in a number

post-thumb

Get all digits in a number with minimum space.

Given a positive integer num, the following function iterates its digits from the most insignificant digit to the most significant one:

def get_digits_right_to_left(num: int):
    while num > 0:
        yield num % 10
        num //= 10

Here’s another way to write it using Python’s divmod function:

def get_digits_right_to_left(num: int):
    while num > 0:
        num, digit = divmod(num, 10)
        yield digit

Can we iterate the digits from the most significant digit to the most insignificant one?

def get_digits(num: int):
    div = 1
    while num // div:
        div *= 10
    div //= 10
    while div:
        yield num // div
        num %= div
        div //= 10

Another version using divmod:

def get_digits(num: int):
    div = 1
    while num // div:
        div *= 10
    div //= 10
    while div:
        digit, num = divmod(num, div)
        div //= 10
        yield digit

Find the number of digits that evenly divide a positive number

Among all the digits of a positive integer num, write a function to determine how many of them evenly divide num. For example, 13204 has 3 digits that evenly divide 13204: 1, 2, and 4 since 13204 % 1 = 13204 % 2 = 0 = 13204 % 4 = 0.

Note that digit 0 does not divide any positive integer.

def count_digits_evenly_divide(num: int) -> int:
    return sum(d != 0 and num % d == 0 for d in get_digits(num))

Self-dividing number

A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number as 128 % 1 = 128 % 2 = 128 % 8 = 0.

A self-dividing number is not allowed to contain the digit zero.

The function below checks if a number is self-dividing:

def is_self_dividing(num: int) -> bool:
    return all(d != 0 and num % d == 0 for d in get_digits(num))

Exercises

comments powered by Disqus