Home > Blockchain >  Error with negative numbers when calculating the sum of digits of the number
Error with negative numbers when calculating the sum of digits of the number

Time:06-13

I gotta calculate the sum of digits of the number. It works for positive numbers but not for negative ones. What should i add here?

n = int(input("Input a number: ")) 
suma = 0
while(n > 0):
    if n > 0:
        last = n % 10
        suma  = last
        n = n // 10
print("The sum of digits of the number is: ", suma)

Input/Output

Input a number: -56
The sum of digits of the number is:  0

CodePudding user response:

The simple fix is to do n = abs(n) then it will work with your code.

And if you really *lazy* you could simplify the approach to this:

n = abs(n)

sum_digit =  sum(int(x) for x in str(n))  # are we cheating?  ;-)

CodePudding user response:

When you pass a negative number, the first while loop's condition while(n > 0): will be false, hence the following code will never be executed and sum's value will never be updated and remain 0.

Use abs() function to get absolute value.

n = abs(int(input("Input a number: ")))
suma = 0
while n > 0:
    if n > 0:
        last = n % 10
        suma  = last
        n = n // 10
print("The sum of digits of the number is: ", suma)

CodePudding user response:

Maybe you could utilize abs and divmod:

def get_int_input(prompt: str) -> int:
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Error: Enter an integer, try again...")


def get_sum_of_digits(num: int) -> int:
    num = abs(num)
    total = 0
    while num:
        num, digit = divmod(num, 10)
        total  = digit
    return total


def main() -> None:
    n = get_int_input("Input an integer number: ")
    sum_of_digits = get_sum_of_digits(n)
    print(f"The sum of digits of the number is: {sum_of_digits}")


if __name__ == "__main__":
    main()

Example Usage 1:

Input an integer number: 123456789
The sum of digits of the number is: 45

Example Usage 2:

Input an integer number: -56
The sum of digits of the number is: 11

Example Usage 3:

Input an integer number: asdf
Error: Enter an integer, try again...
Input an integer number: 2.3
Error: Enter an integer, try again...
Input an integer number: -194573840
The sum of digits of the number is: 41
  • Related