Skip to content

Commit f250d1f

Browse files
Add sum_of_digits implementation
1 parent e2a78d4 commit f250d1f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

maths/add_digits.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
def sum_of_digits(number: int) -> int:
2+
"""
3+
Return the sum of decimal digits of a non-negative integer.
4+
5+
Parameters:
6+
number (int): A non-negative integer whose digits will be summed.
7+
8+
Returns:
9+
int: Sum of the decimal digits of `number`.
10+
11+
Examples:
12+
>>> sum_of_digits(0)
13+
0
14+
>>> sum_of_digits(9)
15+
9
16+
>>> sum_of_digits(12345)
17+
15
18+
"""
19+
if number < 0:
20+
raise ValueError("number must be a non-negative integer")
21+
22+
total = 0
23+
while number:
24+
total += number % 10
25+
number //= 10
26+
return total
27+
28+
29+
if __name__ == "__main__":
30+
# simple demonstration
31+
print(sum_of_digits(12345)) # expected 15

0 commit comments

Comments
 (0)