Skip to content

Fix: Add support for negative numbers in sum_of_digits#3208

Open
javedarham2-coder wants to merge 1 commit into
geekcomputers:masterfrom
javedarham2-coder:feature/fix-negative-digits
Open

Fix: Add support for negative numbers in sum_of_digits#3208
javedarham2-coder wants to merge 1 commit into
geekcomputers:masterfrom
javedarham2-coder:feature/fix-negative-digits

Conversation

@javedarham2-coder

@javedarham2-coder javedarham2-coder commented Jul 17, 2026

Copy link
Copy Markdown

Description:
Currently, passing a negative number to the sum_of_digits() function causes it to enter an infinite loop or produce incorrect results. This PR resolves the bug by ensuring negative signs are safely handled before the sum is calculated.

Solution Implemented:
Instead of mathematically converting the number with abs(), I opted for a Pythonic string-handling approach:
sum(int(digit) for digit in str(n).replace('-', ''))

This cleanly strips the negative sign (if present) and iterates through the remaining digits, completely avoiding edge cases with mathematical signs.

Changes Made:

  • Updated sum_of_digits core logic in both duplicate scripts to handle negative integers.
  • Updated isnumeric() check in the input function to correctly accept negative inputs using .lstrip('-').
  • Updated the function docstrings to clarify behavior with negative inputs.
  • Ensured headers match the Development Guide formatting.

Related Issue:
Closes #3060

Checklist

  • My code follows the project's code style
  • I have commented my code, particularly in hard-to-understand areas
  • I have tested my code locally
  • New tests pass with my changes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add support for negative numbers in sum_of_digits function

1 participant