Python Program for Sum the digits of a given number
Given a number and the task is to find sum of digits of this number in Python.
Input : n = 87
Output : 15
Input : n = 111
Output : 3
Below are the methods to sum of the digits.
Method-1: Using str() and int() methods.: The str() method is used to convert the number to string. The int() method is used to convert the string digit to an integer.
Convert the number to string and iterate over each digit in the string and after converting each digit to integer and add to the sum of the digits in each iteration.
Method-2: Using sum() methods.: The sum() method is used to sum of numbers in the list.
Convert the number to string using str() and strip the string and convert to list of number using strip() and map() method resp. Then find the sum using the sum() method.
Method-3: Using General Approach:
- Get the number
- Declare a variable to store the sum and set it to 0
- Repeat the next two steps till the number is not 0
- Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and add it to sum.
- Divide the number by 10 with help of ‘//’ operator
- Print or return the sum
A. Iterative Approach:
B. Recursive Approach:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course