【发布时间】:2020-06-28 01:29:36
【问题描述】:
我正在写一个递归程序:
public static List<Integer> method(int n)
确定正数n 是否是正数立方体的总和 (> 0)。示例:给定n = 1944 (12^3 + 6^3),程序将按降序返回列表[12, 6]。如果n 不是立方体的总数,程序应该返回一个空列表。
程序应该为第一个元素返回从最高可能值开始的值,然后对其余元素遵循相同的规则。比如n = 1072,程序会返回[10, 4, 2]而不是[9, 7]。
递归应该发生的方法:
private static boolean method(int n, int c, LinkedList<Integer> seen)
其中c 是仍然允许使用的最高号码,soFar 是已经看到的号码列表。
我的代码涵盖了基本情况和递归,但我在循环继续时遇到了问题。通过输入,n = 1944 我的程序将返回列表 [12] 而不是 [12, 6]。
public static List<Integer> method(int n)
{
LinkedList<Integer> result = new LinkedList<Integer>();
int c = (int) Math.cbrt(n);
result.add(c);
method(n, c, result);
return result;
}
private static boolean method(int n, int c, LinkedList<Integer> seen)
{
LinkedList<Integer> result = new LinkedList<Integer>();
boolean b = false;
if (n == 0)
{
return true;
}
else if (c == 0)
{
return false;
}
else
{
int sum = 0;
for (int i : seen)
{
sum += i*i*i;
}
while (b = false)
{
c = (int) Math.cbrt(n - sum);
seen.add(c);
method(n, c, seen);
if (sum == n)
{
result = seen;
return true;
}
else
{
return false;
}
}
}
return false;
}
【问题讨论】:
-
j^3不是 j 立方,它是jbitwise-exclusive-OR3。 -
艾略特,10^3 + 4^3 + 2^3 = 1072
-
请停止删除和转发您的问题。这在 SO 上是不允许的。如果您没有得到答案,请考虑改进它和/或为问题设置奖励。
-
抱歉,不知道如何设置赏金或这意味着什么。我也只是认为人们没有看到这个问题,这就是原因。没有收到太多反馈,谢谢
-
这是因为你的问题很难理解。在您的解释中,您声明一个数字等于 12 立方 + 6 立方,并且返回值应该是列表 [11, 2] 为什么是 11,而不是 12?正是这样的事情让我以前每次看到它都会错过它。
标签: java recursion while-loop linked-list boolean