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).
Related problems
- Product of Digits — Easy
- GC Content — Easy
- Keystroke Count — Easy
- Binary to Decimal — Medium
- RGB to Hex Color — Easy
- IP Address to Integer — Medium