Problem: Compute the sum of digits for the given number as a single digit number.
Example:
sum_of_digits(5674) = 4 (5+6+7+4=22, 2+2=4)
Solution in Python:
def sum_of_digits(n):
"""
Author: Mayur P Srivastava
"""
while n > 9:
n = sum_of_digits2(n)
return n
def sum_of_digits2(n):
sum = 0
while n > 0:
sum += n % 10
n = n // 10
return sum
Concepts Learned: Loops and numbers.
No comments:
Post a Comment