Sum of the digits
Write digit_sum(n) that returns the sum of the digits of the integer n. Negative numbers should work too.
digit_sum(4096) # 19
digit_sum(-25) # 7
digit_sum(0) # 0
Show hint
n % 10 is the last digit of n, and n // 10 drops it.
Show solution
def digit_sum(n):
n = abs(n)
total = 0
while n > 0:
total += n % 10
n //= 10
return total
Each loop peels off the last digit with % 10 and removes it with // 10. abs handles negatives. The one-line version is sum(int(d) for d in str(abs(n))), which is fine too. Both are O(number of digits).
Want a problem like this every day? See today's problem and keep a streak going.