From ac2abad7b6ace8e97422e14ff8bc1868dcac30f9 Mon Sep 17 00:00:00 2001 From: archit7-beep Date: Tue, 2 Dec 2025 20:05:42 +0530 Subject: [PATCH 1/2] fixing negative integers by using the absolute value before computing the digit sum. --- Sum of digits of a number.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/Sum of digits of a number.py b/Sum of digits of a number.py index ba111336965..b10c8e00339 100644 --- a/Sum of digits of a number.py +++ b/Sum of digits of a number.py @@ -24,16 +24,27 @@ def get_integer(): def addition(num): + """ + Returns the sum of the digits of a number. + Negative numbers are handled using the absolute value. + + Examples: + >>> addition(123) + 6 + >>> addition(-789) + 24 + """ Sum = 0 if type(num) is type( None ): # Checks if number type is none or not. If type is none program exits. print("Try again!") sys.exit() + num = abs(num) # Handle negative numbers while num > 0: # Addition- adding the digits in the number. digit = int(num % 10) Sum += digit - num /= 10 + num //= 10 return Sum # Returns sum to where the function is called. @@ -42,4 +53,5 @@ def addition(num): ): # this is used to overcome the problems while importing this file. number = get_integer() Sum = addition(number) - print(f"Sum of digits of {number} is {Sum}") # Prints the sum + abs_display = f" (absolute value: {abs(number)})" if number < 0 else "" + print(f"Sum of digits of {number}{abs_display} is {Sum}") # Prints the sum From 06b37538edf670e42a382d3594d16c9e28858466 Mon Sep 17 00:00:00 2001 From: archit7-beep Date: Tue, 2 Dec 2025 20:08:20 +0530 Subject: [PATCH 2/2] fixing negative integers by using the absolute value before computing the digit sum. --- Sum of digits of a number.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sum of digits of a number.py b/Sum of digits of a number.py index b10c8e00339..ce141531e66 100644 --- a/Sum of digits of a number.py +++ b/Sum of digits of a number.py @@ -31,8 +31,8 @@ def addition(num): Examples: >>> addition(123) 6 - >>> addition(-789) - 24 + >>> addition(-784) + 19 """ Sum = 0 if type(num) is type(