Program to find the sum of all digits of given number in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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
raja
Published on 05-Oct-2020 07:25:28
Advertisements