Find Sum of Digits in Python
What you'll learn
- How to extract digits with
% 10and// 10. - How to sum digits using an accumulator.
- How to handle negatives and zero correctly.
Overview
Take the last digit, add it to total, remove that digit, and repeat.
Two examples
Fixed number and user input variants.
Live preview
See digits and resulting sum instantly.
Interview focus
Clear algorithm + edge cases + complexity.
Prerequisites
Basic Python integers, loops, and input/output.
Live preview
Enter any integer (e.g. 12345 or -802).
Algorithm
1
Convert to nonnegative
n = abs(n)
2
Extract each digit
Use d = n % 10 and n //= 10
3
Add to total
total += d
📜 Pseudocode
Pseudocode
function digit_sum(n):
n = abs(n)
total = 0
while n > 0:
total += n % 10
n //= 10
return total1
Sum of digits (fixed number)
python
def digit_sum(number: int) -> int:
number = abs(number)
total = 0
while number != 0:
total += number % 10
number //= 10
return total
number = 12345
print(f"The sum of digits of {number} is: {digit_sum(number)}")📤 Output
The sum of digits of 12345 is: 15
2
Sum of digits (user input)
python
def digit_sum(number: int) -> int:
number = abs(number)
total = 0
while number != 0:
total += number % 10
number //= 10
return total
number = int(input("Enter a number: ").strip())
print(f"Sum of digits: {digit_sum(number)}")❓ FAQ
Take last digit with n % 10, add it to total, and remove last digit with n //= 10 until n becomes 0.
In base 10, dividing by 10 leaves a remainder from 0 to 9, which is the last digit.
Use abs(n) so the sign does not affect digit sum.
1 + 2 + 3 + 4 + 5 = 15.
O(d), where d is number of digits.
🔄 Input / output examples
| Input | Digit sum | Explanation |
|---|---|---|
| 12345 | 15 | 1+2+3+4+5 |
| -802 | 10 | 8+0+2 |
| 0 | 0 | special case |
Edge cases and pitfalls
n = 0
Return 0
Sum of digits of 0 is 0.
Negative input
Use abs()
Most tasks ignore sign for digit sum.
Large values
Digit-linear work
Each loop handles one digit.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Digit loop | O(d) | O(1) |
Summary
- Use modulo and floor division to process digits.
- Handle negatives via
abs(). - Complexity is linear in number of digits.
Did you know?
Digit sum helps with divisibility tests: a number is divisible by 3 (or 9) exactly when its digit sum is divisible by 3 (or 9).
9 people found this page helpful
