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

Function sum_of_digits

maths/sum_of_digits.py:1–18  ·  view source on GitHub ↗

Find the sum of digits of a number. >>> sum_of_digits(12345) 15 >>> sum_of_digits(123) 6 >>> sum_of_digits(-123) 6 >>> sum_of_digits(0) 0

(n: int)

Source from the content-addressed store, hash-verified

1def sum_of_digits(n: int) -> int:
2 """
3 Find the sum of digits of a number.
4 >>> sum_of_digits(12345)
5 15
6 >>> sum_of_digits(123)
7 6
8 >>> sum_of_digits(-123)
9 6
10 >>> sum_of_digits(0)
11 0
12 """
13 n = abs(n)
14 res = 0
15 while n > 0:
16 res += n % 10
17 n //= 10
18 return res
19
20
21def sum_of_digits_recursion(n: int) -> int:

Callers 1

sum_of_digits_recursionFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected