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

前端 未结 12 1387
说谎
说谎 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:25

    Try this:

    int getSum(int num)
    {
        total = total + num % 10;
        num = num/10;
        if(num == 0)
        {
            return total;
        } else {
            return getSum(num);
        }
    }
    

提交回复
热议问题