【发布时间】:2016-07-10 12:31:16
【问题描述】:
这是我的作业:
将堆叠数定义为某个数的前 n 个正整数之和。前 5 个堆叠的数字是:
1 = 1 3 = 1 + 2 6 = 1 + 2 + 3 10 = 1 + 2 + 3 + 4 15 = 1 + 2 + 3 + 4 + 5请注意,从上面我们可以推断出 7、8 和 9 不是堆叠数字,因为它们不能是从 1 开始的任何正整数序列的总和。编写一个名为 isStacked 的函数,如果它的参数返回 1是堆叠的。否则返回 0。它的签名是:
int isStacked(int n);例如,isStacked(10) 应该返回 1,isStacked(7) 应该返回 0。
这是我的代码:
public class isStacked {
public static void main(String[] arg) {
System.out.println(isStacked(5));
System.out.println(isStacked(6));
System.out.println(isStacked(7));
System.out.println(isStacked(45));
System.out.println(isStacked(12));
}
static int isStacked(int a) {
int b = 0;
for (int i = 0; i <= a; i++) {
b = b + i;
if (b > a)
break;
}
if (b == a)
return 1;
return 0;
}
}
【问题讨论】:
-
您意识到“堆叠数字”只是 triangle numbers 的另一个名称?
-
您可以在 O(1) 时间内完成此操作,而不是 O(
a)。定义n = floor(sqrt(2*a))。那么a被堆叠当且仅当n*(n+1) == 2*a。 (检查溢出。) -
你指的“问题”是什么?