我在Java中玩了一些练习问题。我为下面给出的程序编写了一个递归程序。我的解决方案是正确的,除了挂起(我相信)恢复到活动状态并更改递归方法的值。我还在调试模式下添加了 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));
}
}
上面的屏幕截图来自我的调试器,我已经圈出了线程堆栈。任何人都可以尝试运行该程序,并让我知道问题是什么以及解决方案是什么?我可以想出一个非递归解决方案。
宝慕林4294392
繁星淼淼
相关分类