Issue
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
Solution
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? ;-)
Answered By - Daniel Hao
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.