I am trying to write a function that calculates the sum of digits in a given number. Here are the details:
Input:
Enter a number: 12345
Output:
Sum of digits: 15
Requirements:
- The function should take an integer as input.
- The function should return the sum of the digits of the given integer.
- The function should handle both positive and negative integers.
- For example:
- Input:
12345
should return15
(because 1+2+3+4+5 = 15) - Input:
-12345
should also return15
(ignoring the sign)
- Input:
Additional Information:
- I am looking for solutions that are easy to understand for a beginner.
- If there are any built-in functions in other languages that simplify this task, please mention them.
What I have tried so far:
I have written some code in Python, but I am not sure if it handles all cases correctly. Here is my attempt:
num = 12345
sum = 0
for digit in str(num):
sum = sum + int(digit)
print(sum)
1