Skip to content

Commit cafbbab

Browse files
authored
shortened code using abs() and inplace ops (TheAlgorithms#7191)
n = -n if n < 0 else n --> n = abs(n) n = n // 10 --> n //= 10
1 parent 9278d0c commit cafbbab

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

maths/sum_of_digits.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@ def sum_of_digits(n: int) -> int:
1414
>>> sum_of_digits(0)
1515
0
1616
"""
17-
n = -n if n < 0 else n
17+
n = abs(n)
1818
res = 0
1919
while n > 0:
2020
res += n % 10
21-
n = n // 10
21+
n //= 10
2222
return res
2323

2424

@@ -35,7 +35,7 @@ def sum_of_digits_recursion(n: int) -> int:
3535
>>> sum_of_digits_recursion(0)
3636
0
3737
"""
38-
n = -n if n < 0 else n
38+
n = abs(n)
3939
return n if n < 10 else n % 10 + sum_of_digits(n // 10)
4040

4141

0 commit comments

Comments
 (0)