Integers are used almost everywhere when you write a program. In this article, we will discuss ways to find the sum of digits of a given integer in python.
How to find the sum of digits of an integer?
To find the sum of digits of a number N, we can extract the digits of a number and add them one by one. For this, we will extract the digits from right to left. For extracting the digits, we will divide the number by 10 and store the remainder during each division operation. We will keep dividing the number by 10 until it becomes 0. In this way, we can extract digits one by one.
For example, If we are given the number 12345, we will calculate the sum of digits as follows.
- First, we will initialize a variable sumOfDigits to zero.
- After that, we will divide 12345 by 10.
- After division, we will add reminder 5 to sumOfDigits and update the number to 1234.
- Then, we will divide 1234 by 10.
- After division, we will add reminder 4 to sumOfDigits and update the number to 123.
- Again, we will divide 123 by 10.
- After division, we will add reminder 3 to sumOfDigits and update the number to 12.
- Again, we will divide 12 by 10.
- After division, we will add reminder 2 to sumOfDigits and update the number to 1.
- Now, we will divide 1 by 10.
- After division, we will add reminder 1 to sumOfDigits and update the number to 0.
- As the number has become 0, we will be having the sum of digits of the number 12345 in the variable sumOfDigits i.e. 15.
Implementation In Python
As we have seen above, to find the sum of digits of an integer in python, we just have to divide the number by 10 until it becomes 0. At the same time, we have to add the remainder in each division to obtain the sum of digits. We can implement the program to perform this operation as follows.
def calculate_sum_of_digits(N):
sumOfDigits = 0
while N > 0:
digit = N % 10
sumOfDigits = sumOfDigits + digit
N = N // 10
return sumOfDigits
input_number = 12345
output = calculate_sum_of_digits(input_number)
print("Sum of digits of {} is {}.".format(input_number, output))
input_number = 126
output = calculate_sum_of_digits(input_number)
print("Sum of digits of {} is {}.".format(input_number, output))
Output:
Sum of digits of 12345 is 15.
Sum of digits of 126 is 9.
Conclusion
In this article, we have discussed and implemented a program to find the sum of digits of an integer in Python. To learn more about numbers in python, you can read this article on decimal numbers in python. You might also like this article on complex numbers in python.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.