我是初學者。我無法弄清楚如何寫這將返回1功能,如果有這樣的特性:根據數組中的值返回0或1的方法
arr[0] = arr[1] + arr[2] = arr[3] + arr[4] + arr[5] = arr[6] + arr[7] + arr[8] + arr[9] = ...
否則返回0數組的長度必須n*(n+1)/2
一些n
。
例如,如果輸入數組是{2, 1, 1, 4, -1, -1}
,它返回1,因爲2 = 1 + 1,2 = 4 + 1 + -1
我曾嘗試這樣的:
public static int myArray(int[] a) {
int len = a.length;
if (checkLenght(len)) {
int firstElem = a[0];
int value = 1;
int sum = 0;
for (int i = 1; i <= a.length; i++) {
for (int j = value; j < value + 1; j++) {
sum += a[j];
value++;
}
}
}
return 0;
}
public static boolean checkLenght(int len) {
for (int i = 0; i <= 100; i++) {
if ((i * (i + 1)/2) == len) {
return true;
}
}
return false;
}
感謝提前。
首先,這種方法應該返回true或false,而不是1和0的Java有一個布爾類型,你應該使用它。我們不會做你的功課。嘗試一下。 – 2014-11-22 13:16:21
提示:循環.... – 2014-11-22 13:16:44