我在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)); }} 上面的屏幕截图来自我的调试器,我已经圈出了线程堆栈。任何人都可以尝试运行该程序,并让我知道问题是什么以及解决方案是什么?我可以想出一个非递归解决方案。
2 回答
宝慕林4294392
TA贡献2021条经验 获得超8个赞
你的代码是错误的,你应该有
return getSqrtCount(sqrt, count);
而不是
getSqrtCount(sqrt, count);
否则,递归是毫无意义的,你完全忽略了递归的结果。
繁星淼淼
TA贡献1775条经验 获得超11个赞
您的递归是错误的,因为 在任何情况下,或者即使它深入到递归调用中,也会返回 的值。Java是按值传递的,这意味着修改方法内部的基元的值在该方法之外将不可见。为了纠正这一点,我们可以编写以下递归:count01
private int getSqrtCount(Double value) {
final Double sqrt = Math.sqrt(value);
if((sqrt > 2) && (sqrt % 1 == 0)) {
return getSqrtCount(sqrt) + 1;
}
return 0;
}
添加回答
举报
0/150
提交
取消