关于如何计算验证"if"条件的元素数量的任何想法?

Den*_* A. 7 java

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.

  • 这个答案是唯一的线程安全答案,+ 1. (4认同)

Lef*_*s E 5

我真的不明白你在问什么.但是如果你想让count在方法之外生存,而不是每次调用方法时都创建一个本地副本,你可以将它设置为静态.

static int count=0;
Run Code Online (Sandbox Code Playgroud)


Laf*_*ica 4

从方法中删除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)

  • 这是可行的,但我相信编写递归方法时正确的做法是传入一个计数变量。这将方法的状态保留在调用 stac 上,而不是保留在类变量中。正如其他人提到的,这个版本不是线程安全的。 (2认同)