Add support for negative numbers in sum_of_digits function

Aberta Para iniciantes
#3,060 1 comentário 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
2/5
Tempo estimado
1-3 horas
Facilidade para iniciantes
74/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Pouca atividade
Stack de tecnologia
python
Domínio
backend

Direção de pesquisa

Abra sum_of_digits.py ou o arquivo relevante e localize a função sum_of_digits e o tratamento atual de entradas inteiras. Verifique os casos listados, incluindo valores negativos e zero, e atualize a documentação ou os exemplos, se incluídos; a tarefa estará concluída quando entradas negativas retornarem a soma dos dígitos de seu valor absoluto sem afetar os casos existentes.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

🐛 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

Linguagem predominante
Python
Estrelas
35.4k
Forks
12.9k
Merge médio
2h 37min
PRs com merge (30d)
1

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de geekcomputers/Python

Todas as issues de geekcomputers/Python

Issues semelhantes

Mais issues de Python

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.