How to find the sum of each digit in a given positive integer?
How to find the sum of each digit in a positive integer?
1455
08-Feb-2023
Aryan Kumar
15-Jun-2023There 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.
Rahul Roi
10-Feb-2023I am writing code in “Python” language.
Output:
38
-14563289
Revati S Misra
09-Feb-2023There is a following simple program to find the sum of each digit in a given positive integer,