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

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

    I think it's the shortest so far. The input thing is up too you, though.

     public static int getSum(int input)  {  //example: input=246
           int sum=0;   
           if (input%10==input)  { //246%10=6;  
                  return input%10; //2%10=2
           }
    
           return input%10+getSum((input-input%10)/10); //(246-6)/10=24; 24%10=4
     }
    

提交回复
热议问题