Digital Root without loops Python

后端 未结 6 866
无人及你
无人及你 2021-01-25 07:58
def digit_sum(n):
    \'\'\'(int)->number
    Returns the sum of all the digits in the given integer, n\'\'\'
    if n<10:
        return n
    return n%10 + digit         


        
6条回答
  •  天涯浪人
    2021-01-25 08:31

    Wikipedia lists a simple O(1) formula for the digital root:

    def digit_root(n): 
        return (n - 1) % 9 + 1
    

    This does not take into account an input less than 1, so you can modify as follows, with the assumption that the input is a whole number:

    def digit_root(n): 
        return (n - 1) % 9 + 1 if n else 0
    

    Examples:

    >>> digit_root(1)
    1
    >>> digit_root(11)
    2
    >>> digit_root(235)
    1
    

提交回复
热议问题