Results 1 to 2 of 2

Thread: Array

  1. #1
    Cutie is offline Member
    Join Date
    Mar 2010
    Posts
    1
    Rep Power
    0

    Wink 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. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,457
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Cutie View Post
    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 01:15 PM.

Similar Threads

  1. convert byte array into char array
    By kgkamaraj in forum New To Java
    Replies: 4
    Last Post: 09-13-2011, 11:32 AM
  2. Convert Char Array to String Array
    By Mayur in forum New To Java
    Replies: 8
    Last Post: 10-12-2009, 11:41 AM
  3. Array length and printing out uninitialized array.
    By nicolek808 in forum New To Java
    Replies: 4
    Last Post: 09-10-2009, 09:12 AM
  4. How to transfer 1D array in JAVA to 3D array in C
    By fishwater00 in forum New To Java
    Replies: 0
    Last Post: 07-31-2009, 06:24 PM
  5. Replies: 1
    Last Post: 03-31-2009, 06:40 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •