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

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

 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
Updated on: 2020-10-05T07:26:03+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements