如何编写递归方法来返回int中的数字总和? [英] How to write a recursive method to return the sum of digits in an int?
本文介绍了如何编写递归方法来返回int中的数字总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以这是我到目前为止的代码。
So this is my code so far.
public int getsum (int n){
int num = 23456;
int total = 0;
while (num != 0) {
total += num % 10;
num /= 10;
}
}
问题在于我无法知道如何改变这是一个递归方法
我有一些新的递归,我需要一些帮助来实现这个方法来改变它,所以它的递归。
The problem is that i cant/know how to change this into a recursive method Im kind of new with recursion and i need some help on implementing this method to change it so its recursive.
推荐答案
简短,递归并完成工作:
Short, recursive and does the job:
int getsum(int n) {
return n == 0 ? 0 : n % 10 + getsum(n/10);
}
这篇关于如何编写递归方法来返回int中的数字总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文