- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find the sum of all digits of given number in Python
Suppose we have a number num, we have to find the sum of its digits. We have to solve it without using strings.
So, if the input is like num = 512, then the output will be 8, as 8 = 5 + 1 + 2.
tput will be 8, as 8 = 5 + 1 + 2. To solve this, we will follow these steps −
- sum:= 0
- while num is not same as 0, do
- sum := sum + (num mod 10)
- num:= quotient of num/10
- return sum
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, num): sum=0 while(num!=0): sum = sum+int(num%10) num=int(num/10) return sum ob = Solution() print(ob.solve(512))
Input
512
Output
8
Advertisements