Print Sum of Digits in Given Number using Python
Confronting with numbers is the first thing each one of us has learned in school. However, as we step up high more and more difficult questions based on the same fundamentals seem to appear in our way. It’s the same with programming, using the same fundamentals to find solutions for multiple complex problems. Now the cool thing is, you can be creative in your way eventually coming up with a unique solution. And if you’re able to do this, then you’ve clearly understood how to use programming for others and your good. But keeping that aside, we’ve talked about numbers before. So what if we do simple addition, seems too easy right!. So let’s quickly find out how to Print Sum of Digits in Given Number using python.
With the help of this program, you will be able to find the addition of digits in a number. Practicing these types of questions also helps to get an upper edge in Competitive Programming.
What’s The Approach?
- To store the sum of digits in a number we’ll use a variable
sum
initialized to 0.
- Now we’ll perform a modulo operation with 10 on the number to get the rightmost digit as the remainder.
- After that, we’ll eliminate the rightmost digit by simply dividing our input number by 10.
- The above two instructions will keep executing till the value of our input number becomes less than
0
.
Also Read:Multiply Integers Using Russian Peasant Algorithm in Python
Python Program To Print Sum of Digits in Given Number
Input:
687
Output:
21
# Python program to # compute sum of digits in # number. # Function to get sum of digits def getSum(n): sum = 0 while (n != 0): sum = sum + int(n % 10) n = int(n/10) return sum # Driver code n = 687 print(getSum(n))