使用递归求数字总和 [英] Find Sum of Digits Using Recursion
本文介绍了使用递归求数字总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Java 新手,但我正在编写一个教程,我必须使用递归找到用户输入整数的数字总和.到目前为止,这是我的代码:
Pretty new to Java but I'm working on a tutorial where I have to find the Sum of Digits of a user input integer using recursion. Here is my code so far:
公共课其他{
public static void main(String[] arg) {
Scanner s=new Scanner(System.in);
System.out.println("Enter any integer: ");
int sum=0;
int x=s.nextInt();
int y=recursion(x, sum);
System.out.println("The Sum of the digits is: "+ y);
}
public static int recursion(int y, int sum) {
if(y/10>=1) {
int tempvar =y%10;
int remain=y/10;
sum+=tempvar;
if(remain!=0) {
recursion(remain, sum);
}
return sum;
}
else {
return y;
}
}
所以,如果我输入:123,它返回 3.我在纸上一步一步地完成了这个程序,从逻辑上讲,我想不出我错过的任何东西.
So if I put input: 123, it returns 3. I went through this program on paper step by step and logically I cant think of anything that I missed.
推荐答案
两件事:
- 您忽略了递归调用的结果.
改变
recursion(remain, sum);
到
sum = recursion(remain, sum);
- 在您的基本情况下,您忽略
sum
,这是迄今为止数字的总和,并仅返回您处理的最后一个数字.
- In your base case, you ignore
sum
, which is the sum of the digits so far, and return just the last digit you worked on.
改变
return y;
到
return sum + y;
这篇关于使用递归求数字总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文