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

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

    I see a lot of solutions on here, but not one in which seems as simple as what follows. I've tested it countless times and it works no problem:

    public int sumDigits(int n) {
      if (n == 0){
        return 0;
      }
      else{
        return n%10 + sumDigits(n/10);
      }
    }
    

提交回复
热议问题