Skip to content

Commit 31cabfd

Browse files
Merge pull request #3067 from archit7-beep/master
Fix: Support negative integers in sum of digits function
2 parents 768dd28 + 06b3753 commit 31cabfd

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

Sum of digits of a number.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,27 @@ def get_integer():
2424

2525

2626
def addition(num):
27+
"""
28+
Returns the sum of the digits of a number.
29+
Negative numbers are handled using the absolute value.
30+
31+
Examples:
32+
>>> addition(123)
33+
6
34+
>>> addition(-784)
35+
19
36+
"""
2737
Sum = 0
2838
if type(num) is type(
2939
None
3040
): # Checks if number type is none or not. If type is none program exits.
3141
print("Try again!")
3242
sys.exit()
43+
num = abs(num) # Handle negative numbers
3344
while num > 0: # Addition- adding the digits in the number.
3445
digit = int(num % 10)
3546
Sum += digit
36-
num /= 10
47+
num //= 10
3748
return Sum # Returns sum to where the function is called.
3849

3950

@@ -42,4 +53,5 @@ def addition(num):
4253
): # this is used to overcome the problems while importing this file.
4354
number = get_integer()
4455
Sum = addition(number)
45-
print(f"Sum of digits of {number} is {Sum}") # Prints the sum
56+
abs_display = f" (absolute value: {abs(number)})" if number < 0 else ""
57+
print(f"Sum of digits of {number}{abs_display} is {Sum}") # Prints the sum

0 commit comments

Comments
 (0)