简体   繁体   English

计算并返回java中二维数组中所有偶数的总和

[英]calculate and return the sum of all the even numbers in the 2d-array in java

This Matrix class takes a int[][] as a parameter and saves it in the instance variable.这个 Matrix 类将int[][]作为参数并将其保存在实例变量中。

I need to complete the sumOfEvenNumbers method to calculate and return the sum of all the even numbers in the array.我需要完成sumOfEvenNumbers方法来计算并返回数组中所有偶数的总和。

public class Matrix
{
    private int[][] matrix;

    /**
     * Gets the sum of all the even numbers in the matrix
     * @return the sum of all the even numbers
     */
    public int sumOfEvenNumbers()
    {
        int sum = 0;
        for (int[] i: array)                          
        if (i%2 == 0){ 
        sum += i;        
        }
        return sum;
         // TODO: Return the sum of all the numbers which are even
    }
}

Since you have a 2D array, you'll need to iterate through rows and columns:由于您有一个二维数组,您需要遍历行和列:

int sum = 0;

for (int i=0;i<arr.length;i++)
    for (int j=0;j<arr[i].length;j++)
        if(arr[i][j] % 2 == 0)
            sum += arr[i][j];

return sum;

Alternatively, use a for-each to make this even simpler:或者,使用 for-each 使这更简单:

int sum = 0;

for (int[] innerArr : arr)
    for (int i : innerArr)
        if(i % 2 == 0)
            sum += i;

return sum;

If you are looking to apply this to a two d array, try using a normal for loop which has a column counter and a row counter, then adding up the sums.如果您希望将其应用于两个 d 数组,请尝试使用具有列计数器和行计数器的普通 for 循环,然后将总和相加。 So basically a for loop inside a for loop.所以基本上是一个 for 循环内的 for 循环。 Likewise:同样地:

for(int col=0; col < matrix.length; col++)
{
  for(int row=0; row < matrix.length; row++)
 {
  //your code to access display[row][col]
 }
}

Your current code only supports 1 Dimensional arrays with an enhanced for loop.您当前的代码仅支持具有增强 for 循环的 1 维数组。 Enhanced for loops are great for printing output, but not for assigning/checking values - especially in multi dimensional arrays.增强的 for 循环非常适合打印输出,但不适用于分配/检查值 - 特别是在多维数组中。

Using modulus and branches is expensive and I expect you will find a formula to be quite a bit faster.使用模数和分支是昂贵的,我希望你会发现一个公式要快得多。 Try尝试

public long sumOfEvenNumbers() {
    long sum =0;
    for (int[] arr: array)
        for(int i : arr)                          
            sum += (~i & 1) * i;        
    return sum;
}

If you have (i & 1) * i this will be 0 for even and i for odd.如果你有(i & 1) * i这将是0表示偶数, i表示奇数。 This would effective only add odd numbers.这只会有效地添加奇数。 To flip this for even numbers, we can flip the bits of i and use (~i & 1) * i which is 0 for odd and i for even.要翻转偶数,我们可以翻转i的位并使用(~i & 1) * i ,其中0表示奇数, i表示偶数。

~i flips all the bits of i and is the same as i ^ -1 or -i - 1 or more accurately -i == ~i + 1 ~i翻转的所有位i和是相同的i ^ -1-i - 1或更准确地-i == ~i + 1

package Homeworks;

public class HW89SumEvenIndexEvenRow {
    public static void main(String[] args) {

        int[][] a = {
                {-5,-2,-3,7},
                {1,-5,-2,2},
                {1,-2,3,-4}
        };
        int sum=0;
        for (int i=0;i<a.length;i+=1){
            for (int j=0;j<a[i].length;j++)
                if(i%2==0 ||j%2==0) {
                    sum=sum+a[i][j];
                }
        }
        System.out.println(sum);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM