我正在用 Java 解决一些练习问题。我为下面给出的程序编写了一个递归程序。我的解决方案是正确的,除了挂起的(我相信)恢复到 Activity 状态并更改递归方法的值之外。我还添加了 Debug模式下 Eclipse 的屏幕截图,其中显示了线程堆栈。
package com.nix.tryout.tests;
/**
* For given two numbers A and B such that 2 <= A <= B,
* Find most number of sqrt operations for a given number such that square root of result is a whole number and it is again square rooted until either the
* number is less than two or has decimals.
* example if A = 6000 and B = 7000, sqrt of 6061 = 81, sqrt of 81 = 9 and sqrt of 9 = 3. Hence, answer is 3
*
* @author nitinramachandran
*
*/
public class TestTwo {
public int solution(int A, int B) {
int count = 0;
for(int i = B; i > A ; --i) {
int tempCount = getSqrtCount(Double.valueOf(i), 0);
if(tempCount > count) {
count = tempCount;
}
}
return count;
}
// Recursively gets count of square roots where the number is whole
private int getSqrtCount(Double value, int count) {
final Double sqrt = Math.sqrt(value);
if((sqrt > 2) && (sqrt % 1 == 0)) {
++count;
getSqrtCount(sqrt, count);
}
return count;
}
public static void main(String[] args) {
TestTwo t2 = new TestTwo();
System.out.println(t2.solution(6550, 6570));
}
}
上面的屏幕截图来 self 的调试器,我已经圈出了线程堆栈。任何人都可以尝试运行该程序并让我知道问题是什么以及解决方案是什么?我可以想出一个非递归的解决方案。
最佳答案
你的递归是错误的,因为count
的值在任何情况下都会返回0
或1
,即使它深入递归来电。 Java 是按值传递的,这意味着修改方法内部原语的值在该方法外部是不可见的。为了纠正这个问题,我们可以编写以下递归:
private int getSqrtCount(Double value) {
final Double sqrt = Math.sqrt(value);
if((sqrt > 2) && (sqrt % 1 == 0)) {
return getSqrtCount(sqrt) + 1;
}
return 0;
}
关于java - 由于线程挂起而导致递归问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55326600/