实际上我的目标是找到 super 否,例如我将得到2个值n,k,其中n = 148且k = 3,所以我必须形成p = 148148148,然后添加p的数字直到我得到一个否(ans = 3)这是我尝试过的......
import java.util.*;
public class RecurrsiveDigitSum {
public int check(int n) {
int s = 0;
int d;
while(n>0) {
d = n%10;
s = s+d;
n = n/10;
System.out.println(s);
}
if(s/10 !=0){
check(s);
}
return s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
int sum;
RecurrsiveDigitSum obj = new RecurrsiveDigitSum();
sum = obj.check(n);
System.out.println(sum);
sum = sum * k;
System.out.println(sum);
int s1 = obj.check(sum);
System.out.println(s1);
}
}
但这里的问题是,即使我的 s = 4 最终它也只是返回已找到的 s 的第一个值,所以请帮助我 friend 们
最佳答案
必须将 return 放在递归调用之前。
if(s/10 !=0){
return check(s);
}
如果不写,调用函数的结果将是loss,并且返回s的结果而不是check(s)。
我稍微改进了你的解决方案。
public int check(int n) {
int s = 0;
while(n>0) {
s += n%10;
n /= 10;
}
if(s/10 != 0){
return check(s);
}
return s;
}
关于java - 如何在java中以递归fn返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52800080/