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 conerting 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:
- Python Program for Check if all digits of a number divide it
- Python Program to check whether it is possible to make a divisible by 3 number using all digits in an array
- Python Program to create an OTP by squaring and concatenating the odd digits of a number
- Python | Sum of number digits in List
- Python - Remove all digits before given Number
- Python Program for Difference between sums of odd and even digits
- Python Program to print all Possible Combinations from the three Digits
- Python Program to extracts elements from the list with digits in increasing order
- Python program to extract only the numbers from a list which have some specific digits
- Python Program for Efficient program to print all prime factors of a given number
- Check if the sum of digits of a number N divides it
- Python | Sort list of numbers by sum of their digits
- Python program to find number of m contiguous elements of a List with a given sum
- Python | Ways to remove numeric digits from given string
- Python | Remove element from given list containing specific digits
- Python | Extract digits from given string
- Python Program for Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!
- Python Program for How to check if a given number is Fibonacci number?
- Check whether the sum of absolute difference of adjacent digits is Prime or not
- Python program to find all possible pairs with given sum
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.