2014-11-22 25 views
0

我是初學者。我無法弄清楚如何寫這將返回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; 
} 

感謝提前。

+5

首先,這種方法應該返回true或false,而不是1和0的Java有一個布爾類型,你應該使用它。我們不會做你的功課。嘗試一下。 – 2014-11-22 13:16:21

+2

提示:循環.... – 2014-11-22 13:16:44

回答

1

我嘗試將輸入分成兩組,三組.... ....元素。爲此,我使用pointer來顯示此分區中有多少元素。冷杉是2.那麼它是三,...。我使用temp數字來計算在這個分區中是否有足夠的元素。在每個分區中有足夠的元素之後,我只需檢查該分區的元素的總和。

這應該做的工作:

所有的
public static int myArray(int[] a) { 
    int len = a.length; 
    if (checkLenght(len)) { 
     int firstElem = a[0]; 
     int pointer = 2;      // pointer that will be 2, 3, 4 , ... 
     int sum = 0;       // sum of element in each partition 
     int temp = 0;      // a temp value to check if I reach desirable number of element in this partition or not. 
     for (int i = 1; i < a.length; i++) { // i<=a.length give you exception. 
      temp++;       
      sum += a[i]; 
      if (temp == pointer) {   // check if I have enough element. 
       pointer++;     // plus pointer by one 
       temp = 0;     // reset temp 
       if (sum != firstElem)  // if in any of those partitions my needs doesnt meet I return zero. 
        return 0; 
       sum = 0;      // reset sum 
      } 
     } 
     return 1; 
    } 
    return 0; 
} 
+0

爲了真正幫助,我認爲你應該解釋你的答案是如何工作的。 – ale64bit 2014-11-22 13:43:49

+0

@kaktusito如果你想要真相,我想知道如何解釋這一點,英語不是我的母語,我不擅長它,所以我只是想知道如何用英語解釋它。 – Lrrr 2014-11-22 13:45:37

+0

非常感謝@AliAmiri按預期工作 – Anish 2014-11-22 13:53:32