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

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

    Short, recursive and does the job:

    int getsum(int n) {
       return n == 0 ? 0 : n % 10 + getsum(n/10);
    }
    

提交回复
热议问题