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)
| 47 | |
| 48 | |
| 49 | def 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 | |
| 77 | def main() -> None: |