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

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

    This works for positive numbers.

    public int sumDigits(int n) {
      int sum = 0;
      if(n == 0){
      return 0;
      }
      sum += n % 10; //add the sum
      n /= 10; //keep cutting
      return sum + sumDigits(n); //append sum to recursive call
    }
    

提交回复
热议问题