2016-11-16 28 views
1

我試圖用蠻力,所以我能理解來回答這個問題;回事:產品的,其他號碼InterviewCake回答使用蠻力

https://www.interviewcake.com/question/java/product-of-other-numbers

但問題是我不明白爲什麼我的邏輯不起作用。這是我迄今爲止的嘗試:

public class EveryInteger { 

    public static void main(String[] args) { 

     int a1[] = {1, 7, 3, 4}; 
     int a2[] = new int[4]; 
      for(int i =0; i<a1.length; i++){ 
      int index = a1[i]; 
      int sum = 0; 

      for(int j =0; j<a1.length; j++){ 
       if(a1[i]==a1[j]){ 
        continue; 
       } 

       sum = index * a1[j]; 
       a2[i] = sum; 
       System.out.println(a2[i]); 
      } 
      } 
    } 

任何人都可以請告訴我你是如何解決這個問題,使用兩個for循環?

回答

0

您正在將sum指定爲a2並將其打印在內部循環中,這是不正確的。嘗試做外循環,而不是:

public class EveryInteger { 

    public static void main(String[] args) { 
     int a1[] = {1, 7, 3, 4}; 
     int a2[] = new int[4]; 
      for(int i =0; i<a1.length; i++){ 
      int sum = 1; 

      for(int j =0; j<a1.length; j++){ 
       if(a1[i]==a1[j]){ 
        continue; 
       } 
       sum *= a1[j]; 
      } 
      a2[i] = sum; 
      System.out.println(a2[i]); 
      } 
    } 
} 
3

有幾個問題在這裏:

// defining an array like this is confusing because the type is not immediately clear, rather use int[] a1 = ... 
int a1[] = {1, 7, 3, 4}; 
// a2 should always have the same length as a1, so use a1.length 
int a2[] = new int[4]; 
for(int i =0; i<a1.length; i++){ 
    // index is a little confusing, since it's not the index but the value at i 
    int index = a1[i]; 
    // sum is also confusing, since you're working with multiplication here 
    // Additionally with multiplication involved, initialize that to 1 
    int sum = 0; 

    for(int j =0; j<a1.length; j++){ 
     // comparing only j and i would be sufficient here without accessing the array twice 
     if(a1[i]==a1[j]){ 
      continue; 
     } 

     // Instead of accumulating the product you reassign it every time, effectively deleting the previous value. 
     sum = index * a1[j]; 
     a2[i] = sum; 
     System.out.println(a2[i]); 
    } 
} 

一個解決方案可能是這樣的:

int[] input = {1,7,3,4}; 
int[] output = new int[input.length]; 

for(int i = 0; i < input.length; i++) { 
    // Accumulates the multiplications. 
    int acc = 1; 
    for(int j = 0; j < input.length; j++) { 
    // check, if not at the same index. 
    if(j != i) { 
     // only then multiply the current number with the accumulator. 
     acc *= input[j]; 
    } 
    } 
    // finally write the accumulated product to the output array. 
    output[i] = acc; 
} 

System.out.println(Arrays.toString(output)); 

如期望的結果:

[84, 12, 28, 21]