Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a recursive method to return the sum of digits in an int?

Tags:

java

recursion

So this is my code so far.

    public int getsum (int n){
        int num = 23456;
        int total = 0;
        while (num != 0) {
            total += num % 10;
            num /= 10;
        }
    } 

The problem is that i cant/know how to change this into a recursive method Im kind of new with recursion and i need some help on implementing this method to change it so its recursive.

like image 535
user1268088 Avatar asked Nov 28 '22 22:11

user1268088


2 Answers

Short, recursive and does the job:

int getsum(int n) {
   return n == 0 ? 0 : n % 10 + getsum(n/10);
}
like image 173
Naytzyrhc Avatar answered Nov 30 '22 22:11

Naytzyrhc


Here it is,

//sumDigits function
int sumDigits(int n, int sum) {    
    // Basic Case to stop the recursion
if (n== 0)  {
        return sum;
    } else {
        sum = sum + n % 10;  //recursive variable to keep the digits sum
        n= n/10;
        return sumDigits(n, sum); //returning sum to print it.
    }
}

An example of the function in action:

public static void main(String[] args) {
     int sum = sumDigits(121212, 0);
     System.out.println(sum);
}
like image 30
Rahul Borkar Avatar answered Nov 30 '22 22:11

Rahul Borkar