Sum of Digits
Easy · rating 950 · math, strings
Read a non-negative integer n. Print the sum of its digits.
Constraints: 0 ≤ n ≤ 1018
Editorial
Sum of Digits adds up a number's decimal digits. Peel them off with % 10 and // 10, or iterate the string form and sum the digit values.
total = 0
while n:
total += n % 10
n //= 10
print(total)Complexity
Time: O(d) in the number of digits. Space: O(1).