sum of digits Algorithm

The Sum of Digits algorithm is a simple, yet effective technique used in various applications such as digital root calculation, checksums, and barcodes. This algorithm involves taking the individual digits of a number, adding them together, and repeating the process until a single-digit result is obtained. It is particularly useful as a basic tool for error detection and validation in data transmission, as well as a method for simplifying calculations in number theory and recreational mathematics. To implement the sum of digits algorithm, one can start by converting the given number into a string or array of its digits. Then, iterate through the digits, summing them together as you go along. If the sum obtained is a two-digit number or greater, repeat the process until a single-digit result is achieved. The final result is the sum of digits, which serves as a concise representation of the original number and can be used for various purposes, such as determining the digital root or verifying the integrity of data.
def sum_of_digits(n: int) -> int:
    """
    Find the sum of digits of a number.

    >>> sum_of_digits(12345)
    15
    >>> sum_of_digits(123)
    6
    """
    res = 0
    while n > 0:
        res += n % 10
        n = n // 10
    return res


if __name__ == "__main__":
    print(sum_of_digits(12345))  # ===> 15

LANGUAGE:

DARK MODE: