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

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

    public static int digitSum (int n)
      { 
        int r = n%10;       //remainder, last digit of the number
        int num = n/10;     //the rest of the number without the last digit
        if(num == 0)
        {
          return n;
        } else {
          return digitSum (num) + r;
        }} 
    

提交回复
热议问题