Add support for negative numbers in sum_of_digits function

Open Beginner friendly
#3,060 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
74/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Quiet
Tech stack
python
Domain
backend

Research direction

Open sum_of_digits.py or the relevant file and locate the sum_of_digits function and its current handling of integer input. Verify the listed cases, including negative values and zero, and update the documentation or examples if included; done means negative inputs return the digit sum of their absolute value without breaking existing cases.

Written by the indexing model from the issue text.

Description

🐛 Current Behavior
The sum_of_digits() function currently only works with non-negative integers. When a negative number is passed, it enters an infinite loop or produces incorrect results.

python:

Current implementation fails with negative numbers

sum_of_digits(-123) # Does not work correctly

✅ Expected Behavior
The function should handle negative numbers by computing the sum of digits using the absolute value.

python
sum_of_digits(-123) # Should return 6 (1 + 2 + 3)
sum_of_digits(-456) # Should return 15 (4 + 5 + 6)

💡 Proposed Solution
Add abs() to handle negative numbers in the sum_of_digits function:

def sum_of_digits(n: int) -> int:
"""
Compute the sum of the digits of an integer.

Args:
    n: An integer (negative values are converted to absolute).

Returns:
    Sum of digits of the absolute value of the number.

Examples:
    >>> sum_of_digits(123)
    6
    >>> sum_of_digits(-789)
    24
"""
n = abs(n)  # Handle negative numbers
total = 0

while n > 0:
    total += n % 10
    n //= 10

return total

📋 Additional Improvements (Optional)

Update docstring to clarify behavior with negative numbers
Add doctests for negative numbers
Update main() to display absolute value when input is negative:

python
abs_display = f" (absolute value: {abs(number)})" if number < 0 else ""
print(f"The sum of the digits of {number}{abs_display} is: {result}")

🧪 Test Cases

sum_of_digits(123) → 6
sum_of_digits(-123) → 6
sum_of_digits(0) → 0
sum_of_digits(-999) → 27

sum_of_digits.py (or the relevant file name)

🏷️ Labels
enhancement, good first issue, bug

Dominant language
Python
Stars
35.4k
Forks
12.9k
Avg merge
2h 37m
Merged PRs (30d)
1

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from geekcomputers/Python

All issues in geekcomputers/Python

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.