The input number can be negative. In this case, we’ll change its sign (the sum of the digits of the numbers and is the same).
Let's implement the recursive function , that computes the sum of the digits of number , according to the recursive relation:
if n < 10, then the sum of its digits equals ;
otherwise, compute the sum of the digits of the number and add to it the last digit of the number .
This problem can also be solved using a loop (without using recursion).
Example
Algorithm implementation
The function sum computes the sum of the digits of the number .
int sum(int n)
{
if (n < 10) return n;
return n % 10 + sum(n / 10);
}The main part of the program. Read the input value of .
scanf("%d",&n);If the number is negative, then change its sign to the opposite.
if (n < 0) n = -n;Compute and print the sum of the digits of the number .
res = sum(n);
printf("%d\n",res);Algorithm implementation — iteration
Read the input value of .
scanf("%d",&n);If the number is negative, then change its sign to the opposite.
if (n < 0) n = -n;In the variable , find the sum of the digits of the number .
sum = 0;Iterate through the digits of the number . Add each digit of to the sum .
while (n > 0)
{
sum = sum + n % 10;
n = n / 10;
}Print the answer.
printf("%d\n",sum);Java implementation
import java.util.*;
public class Main
{
static int sum(int n)
{
if (n < 10) return n;
return n % 10 + sum(n / 10);
}
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
if (n < 0) n = -n;
int res = sum(n);
System.out.println(res);
con.close();
}
}Python implementation
Read the input value of .
n = int(input())If the number is negative, then change its sign to the opposite.
if n < 0: n = -n;Iterate over the digits of . Add each digit of to the sum .
sum = 0
while n > 0:
sum = sum + n % 10;
n = n // 10;Print the answer.
print(sum)Python implementation — function
The function sum computes the sum of the digits of the number .
def sum(n):
if n < 10: return n
return sum(n // 10) + n % 10The main part of the program. Read the input value of .
n = int(input())If the number is negative, then change its sign to the opposite.
if n < 0: n = -n;Compute and print the sum of the digits of the number .
print(sum(n))Python implementation — string
Read the input value of .
n = int(input())If the number is negative, then change its sign to the opposite.
if n < 0 : n = -nConvert the integer number to a string: . Then from the string, create a list of digits. For example, if n = 123, then str(n) = "123" and list(map(int, str(n))) = [1, 2, 3]. The map function applies the int function to each character of the string , converting each character into an integer value.
s = list(map(int,str(n)))Print the answer, the sum of the integers in the list .
print(sum(s))