David
David

Reputation: 173

How to read an integers numbers individually

Hello guys I have a quick question. So I have an assignment where I have to create a program that recursively calculates the sum of all the digits in an integer. IE integer 123 (1+2+3) = 6. How do I make it start at the first number and keep going until there is no other number left? This is what i have so far....

import java.util.*;

public class sum 
{    
    /**
     * @param args
     */
    public static void main(String[] args) 
    {           
        System.out.println(sumDigits(123))   
    }

    public static  int sumDigits(int n)
    {
        while (n.hasNext())
        {
            return n.charAt(n.length) + sumDigits(n.charAt((n.length - 1)))
        }
    }
}

Now I know I'm using (hasNext and charAt which i'm not supposed to...) but what is the equivalent for the int?

Upvotes: 2

Views: 756

Answers (6)

András Hummer
András Hummer

Reputation: 972

Sorry, missed the requirement for being recursive.

public static int sumDigits(int n) {
  int sum = sumDigits0(n, 0);
  if (sum < 10) {
    return sum;
  }
  return sumDigits(sum);
}

private static int sumDigits(int n, int sum) {
  if (n == 0) {
    return sum;
  }
  return sumDigits(n/10, sum + (n%10));
}

Upvotes: 0

A4L
A4L

Reputation: 17595

You can try this using recursion:

public int sumDigits(int n) {
    int abs = Math.abs(n), lastdigit = 0, sum = 0;
    if(n != 0) {
        lastdigit = abs % 10;
        sum = lastdigit + sumDigits(abs / 10);
    }
    return sum;
}

here some testeing:

@Test
public void sumDigits() {
    Assert.assertEquals(3, sumDigits(12));
    Assert.assertEquals(6, sumDigits(123));
    Assert.assertEquals(10, sumDigits(1234));
    Assert.assertEquals(15, sumDigits(12345));
    Assert.assertEquals(21, sumDigits(123456));
    Assert.assertEquals(28, sumDigits(1234567));
    Assert.assertEquals(28, sumDigits(7654321));
    Assert.assertEquals(28, sumDigits(-7654321));
    Assert.assertEquals(44, sumDigits(2056239854));
    Assert.assertEquals(46, sumDigits(Integer.MAX_VALUE)); // 2147483647
}

Upvotes: 1

Tarsem Singh
Tarsem Singh

Reputation: 14199

1st way :

public static int sumDigits(int n) {                
            int validate = n % 10;
            int digit = n / 10;
            if (validate == 0) 
                return validate;
            return validate + sumDigits(digit);
        }

2nd Way :

public static int sumDigits(int n) {    
            String[] temp = Integer.toString(n).split("");
            int sum = 0;
            for (int i = 1; i < temp.length; i++)// i=1 to skip first first empty value
                sum += Integer.parseInt(temp[i]);    
            return sum;   
         }

Test:

System.out.println("" + sumDigits(123)); // For both cases same O/p

Output:

6

Upvotes: 0

anguyen
anguyen

Reputation: 477

How to do a problem recursively

Think about the base case: if the num<10, then we just want to return that digit

What are the other cases? In this case, there is only one other case: we have more digits and we need to add the first digit and then process the rest

public int sumDigits(int n){
     return sumDigitsHelper(n,0);
}

public int sumDigitsHelper(int n, int sum){
     if(n<10)
          return sum+n;
     return sumDigitsHelper(n/10,sum+n%10);

}

Upvotes: 0

aga
aga

Reputation: 29416

Simple recursive solution: you start from the end of your number and on each step you get the last digit of your number (which is m) and your number divided by 10, which is next. If on some step you got 0 as a result of n / 10 - then it's the end of recursion, you can return your remainder. Otherwise you call your function again with next.

public static  int sumDigits(int n)
{
    int m = n % 10, next = n / 10;
    if (next == 0) {
        return m;
    }
    return m + sumDigits(next);
}

Upvotes: 4

Henry
Henry

Reputation: 43738

There are two operations you will need:

getting the last digit of a number: n % 10

getting a number without the last digit: n / 10

Using these two operations in a loop will get you all the digits of the number.

Upvotes: 5

Related Questions