private static int chain(int n){
int count = 0;
while(n > 1){
if(n % 2 == 0){
count++; //the value is not stored
return chain(n/2);
}
count++; //same thing
return chain(3*n+1);
}
return count; //prints the initial value (0)
}
}
Run Code Online (Sandbox Code Playgroud)
我需要打印链方法重新出现的次数.
ars*_*jii 10
这个怎么样:
public static int chain(int n) {
return chain(n, 0);
}
private static int chain(int n, int count) {
if (n > 1) { // no need for a while-loop, it will never get past 1 iteration
if (n % 2 == 0) {
return chain(n / 2, count + 1);
}
return chain(3 * n + 1, count + 1);
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
对我来说,这似乎比在方法之外声明静态字段更清晰,主要是因为我不想担心每次调用时都必须将静态字段重置为0 chain.
我真的不明白你在问什么.但是如果你想让count在方法之外生存,而不是每次调用方法时都创建一个本地副本,你可以将它设置为静态.
static int count=0;
Run Code Online (Sandbox Code Playgroud)
从方法中删除count变量,并使其成为类的静态成员。为了防止重复您的lsef(DRY原则),您应该增加count方法顶部的变量。
private static int count = 0;
private static int chain(int n) {
count++;
while(n > 1) {
if(n % 2 == 0) {
return chain(n/2);
}
return chain(3*n+1);
}
return count;
}
Run Code Online (Sandbox Code Playgroud)