MCPcopy Create free account
hub / github.com/geekcomputers/Python / sum_of_digits

Function sum_of_digits

sum_of_digits_of_a_number.py:49–74  ·  view source on GitHub ↗

Compute the sum of the digits of an integer. Args: n: Non-negative integer. If the integer is negative, it is converted to positive before computing the sum. Returns: Sum of digits of the number. Examples: >>> sum_of_digits(123) 6 >

(n: int)

Source from the content-addressed store, hash-verified

47
48
49def sum_of_digits(n: int) -> int:
50 """
51 Compute the sum of the digits of an integer.
52
53 Args:
54 n: Non-negative integer.
55 If the integer is negative, it is converted to positive before computing the sum.
56
57 Returns:
58 Sum of digits of the number.
59
60 Examples:
61 >>> sum_of_digits(123)
62 6
63 >>> sum_of_digits(405)
64 9
65 >>> sum_of_digits(-789)
66 24
67 """
68 n = abs(n) # FIX: handle negative numbers
69 total = 0
70 while n > 0:
71 # Add last digit and remove it from n
72 total += n % 10
73 n //= 10
74 return total
75
76
77def main() -> None:

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected