我已經解決了UVa Online Judge上的一個3 * N + 1問題(100),但是這裏有一件事我不明白,但是它與Java有關,我猜測不是與算法本身有關。因此,這裏的代碼:爲什麼變量初始化是多餘的?
private static int maxCycleLength(int lo, int hi) {
maxLength = 0;
int n = 0;
int length = 0;
for (int i = lo; i <= hi; i++) {
// It's the first time we're computing the cycle length for n
if (lengths[i] == 0) {
n = i;
length = 1;
while (n != 1) {
if ((n % 2) == 0) {
n = n >> 1;
length++;
}
else {
n = 3 * n + 1;
n = n >> 1;
length += 2;
}
}
lengths[i] = length;
}
// Otherwise we just look it up
else
length = lengths[i];
// Check if the current cycle length is the maximum
if (length > maxLength)
maxLength = length;
}
return maxLength;
我不明白:我的IDE(IDEA)告訴我,在這段代碼變量的初始化n
和length
是多餘的,但是,maxLength
必須初始化如果我不這樣做,它不會編譯。
爲什麼這麼說? maxLength
與n
和length
有何不同?
順便說一句:以相同的效率一次可以放置int長度;緊接在for後面{'和'int n:i;'' –