1. Member
Join Date
Mar 2010
Posts
1
Rep Power
0

## Array

how to solve this question?

Question: Write a function that takes as parameter an integer value and returns the sum of the digits in the integer, e.g. if the integer is 4123, then the function returns value 10(i.e. 4+1+2+3).Note that the integer can contain any number of digits.

2. Originally Posted by Cutie
how to solve this question?

Question: Write a function that takes as parameter an integer value and returns the sum of the digits in the integer, e.g. if the integer is 4123, then the function returns value 10(i.e. 4+1+2+3).Note that the integer can contain any number of digits.
This can easily be solved using a little recursive method; a few simple observations:

1) let S(n) be the function we're looking for.
2) the sum of the digits in the number zero (0) equals 0, i.e. S(0) == 0
2) let a number be written as the digits d_1 d_2 ... d_n then the sum of all the digits equals S(d_1 d_2 ... d_n-1)+d_n

Observations 2) and 3) lead to the following function:

Java Code:
```int S(int n) {
if (n == 0) return 0; // observation 2)
return S(n/10)+n%10; // observation 3)
}```
As you can see no array is needed at all.

kind regards,

Jos
Last edited by JosAH; 03-07-2010 at 02:15 PM.