how to find sum of digits of a number code example
Example 1: Determine the sum of al digits of n
def sum_of_digits(n):
sum = 0
while (n != 0):
sum = sum + int(n % 10)
n = int(n/10)
return sum
Example 2: Write a function digitsum that calculates the digit sum of an integer. The digit sum of an integer is the sum of all its digits.
function digSum(n) {
let sum = 0;
let str = n.toString();
console.log(parseInt(str.substring(0, 1)));
for (let i = 0; i < str.length; i++) {
sum += parseInt(str.substring(i,i+1));
}
return sum;
}
Example 3: sum of digits
num = [int(d) for d in input("Enter the Number:")]
sum = 0
for i in range(0, len(num)):
sum = sum + num[i]
print("Sum of Digits of a Number: {}".format(sum))
# This code is contributed by Shubhanshu Arya (Prepinsta Placement Cell Student)