How to find the sum of each digit in a given positive integer?
How to find the sum of each digit in a given positive integer?
Jr. Software Developer
I am a software developer at MindStick soft. Pvt. ltd. I joined this company in august 2021 after completing my post-graduation course. I love to see the historical places of my country.
There are many ways to find the sum of each digit in a positive integer. Here are a few methods:
Method 1: Using a loop
For example, to find the sum of the digits in the number 12345, we would do the following:
Code snippet
This would give us a sum of 15.
Method 2: Using the
sum()functionThe
sum()function in Python can be used to find the sum of a list of numbers. We can use this function to find the sum of the digits in a number by converting the number to a list of digits first.For example, to find the sum of the digits in the number 12345, we would do the following:
Code snippet
This would give us a sum of 15.
Method 3: Using the
reduce()functionThe
reduce()function in Python can be used to apply a function to all the elements of a list, and then return the result. We can use this function to find the sum of the digits in a number by using thesum()function as the function to apply.For example, to find the sum of the digits in the number 12345, we would do the following:
Code snippet
This would give us a sum of 15.
Which method you use to find the sum of the digits in a positive integer depends on your personal preference and the programming language you are using.
I am writing code in “Python” language.
Output:
38
-14563289
There is a following simple program to find the sum of each digit in a given positive integer,