Python Sum of Digits Calculator
Compute the sum of individual digits in an integer using mathematical operators in Python.
How it Works
Calculating the sum of digits involves extracting each digit of a number sequentially and accumulating the values.
In Python, this can be achieved using two main techniques: arithmetic loops using modulo `% 10` and floor division `// 10`, or string conversion iteration.
The arithmetic approach operates in O(log n) time and O(1) space, making it efficient and language-independent.
Source Code
Arithmetic sum of digits function with absolute values to support negative numbers.
sum_of_digits.py
Try in Editordef sum_digits(n):
n = abs(n)
total = 0
while n > 0:
total += n % 10 # Extract last digit
n //= 10 # Remove last digit
return total
print("Sum of digits for 12345:", sum_digits(12345))
print("Sum of digits for 908: ", sum_digits(908))Terminal Output
Sum of digits for 12345: 15
Sum of digits for 908: 17Real-world Applications
- Digital root calculations in mathematics
- Checksum validation and hashing algorithms
- Aesthetic and numerological coding puzzles
Frequently Asked Questions
Can this be done in a single line in Python?
Yes! You can convert the number to string, cast back each character to integer, and sum them: `sum(int(d) for d in str(abs(n)))`.
More Examples
Python Palindrome Checker
Check if a string or number is a palindrome (reads the same backward as forward) using Python slicing.Python Armstrong Number Checker
Verify if a number is an Armstrong (narcissistic) number where the sum of its own digits raised to the power of the number of digits equals the number itself.