【发布时间】:2019-06-02 10:33:47
【问题描述】:
我在 Codewars 上完成了 Kata,这是乘法持久性方法。对于那些不了解挑战的人,它如下所示:
该函数接受一个正参数 num 并返回其乘法持久性,这是您必须将 num 中的数字相乘直到达到单个数字的次数。例如:
persistence(39) === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(999) === 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) === 0 // because 4 is already a one-digit number
我的有效解决方案使用两个 while 循环(如下)。我现在正在尝试使用递归编写方法。但是,我发现我可能会遇到线程问题(因为我需要返回数字相乘的次数)。是否可以使用递归?如果有,怎么做?
这是我使用迭代的代码:
public static int persistence(long n) {
int count = 0;
if(n < 10) return count;
long num = 1;
while(n >= 10) {
while(n != 0) {
num*=(n % 10);
n/=10;
}
n = num;
num = 1;
count++;
}
return count;
}
到目前为止,我只知道:
- 基本情况是
这是如果 n 是单个数字。if(n < 10) return 0;
递归案例是我遇到的问题。谢谢!
【问题讨论】:
-
“线程问题”:如何?您的代码是否在并行线程上运行?如果是,你能给出一个具体的背景吗?