Back to Practice Dashboard
Python BasicsEasy

Sum of digits of a number

Learn how to solve the 'Sum of digits of a number' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

Write a function sum_of_digits(n) that takes a non-negative integer n and returns the sum of its digits. For example, the digits of 123 are 1, 2, and 3, and their sum is 6.

Constraints
  • 0 <= n <= 10^9

Examples

Example 1
Input
n = 123
Output
6
Explanation

1 + 2 + 3 = 6.

Example 2
Input
n = 9999
Output
36
Explanation

9 + 9 + 9 + 9 = 36.

Example 3
Input
n = 0
Output
0
Explanation

The only digit is 0, so the sum is 0.

Need a Hint?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor