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

前端 未结 12 1364
说谎
说谎 2020-12-06 14:34

So this is my code so far.

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


        
12条回答
  •  隐瞒了意图╮
    2020-12-06 15:29

    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);
    }
    

提交回复
热议问题