Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find the sum of all digits of given number in Python
Finding the sum of digits of a number is a common programming problem. We need to extract each digit from the number and add them together without converting the number to a string.
So, if the input is like num = 512, then the output will be 8, as 8 = 5 + 1 + 2.
To solve this, we will follow these steps ?
- Initialize sum = 0
- while num is not equal to 0, do
- sum = sum + (num mod 10)
- num = quotient of num/10
- return sum
Method 1: Using Modulo and Division
We extract the last digit using modulo 10, add it to sum, then remove the last digit by integer division ?
class Solution:
def solve(self, num):
digit_sum = 0
while num != 0:
digit_sum = digit_sum + (num % 10)
num = num // 10
return digit_sum
ob = Solution()
print(ob.solve(512))
8
Method 2: Using Recursion
We can solve this problem recursively by adding the last digit to the sum of remaining digits ?
def sum_of_digits(num):
if num == 0:
return 0
return (num % 10) + sum_of_digits(num // 10)
print(sum_of_digits(512))
print(sum_of_digits(1234))
print(sum_of_digits(999))
8 10 27
Method 3: Simple Function Approach
A clean function implementation without using a class ?
def digit_sum(num):
total = 0
while num > 0:
total += num % 10
num //= 10
return total
# Test with different numbers
numbers = [512, 1234, 999, 7, 0]
for number in numbers:
print(f"Sum of digits in {number}: {digit_sum(number)}")
Sum of digits in 512: 8 Sum of digits in 1234: 10 Sum of digits in 999: 27 Sum of digits in 7: 7 Sum of digits in 0: 0
How It Works
The algorithm works by repeatedly extracting the rightmost digit using the modulo operator (%) and then removing it using integer division (//):
- num % 10 gives the last digit
- num // 10 removes the last digit
- Continue until num becomes 0
Conclusion
The modulo and division approach is the most efficient method to find the sum of digits without using strings. Use recursion for elegant code or simple iteration for better performance.
