Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

java - Multiply elements in an array in specific positions? (the first element with the last element etc)

Let's say I have an array {1, 1, 2, 3, 4, 5} and I want to multiply the first element with the last, the second element with the second to last etc and then calculate the sum. So I would multiply 1 with 5, 1 with 4, and 2 with 3 so that the sum would be 15.

This is the code I have so far but it multiplies all of the elements with each other so the sum is 120 instead of 15. Any advice on how I could change it? Do I have to split up the array first before I start multiplying the elements with each other?

    public static void main(String[] args) {
    int [] array = new int [] {1, 1, 2, 3, 4, 5};
    int sum = 1;
    for (int i = 0; i < array.length; i++) {
        sum = sum * array[i];
    }
    System.out.println(sum);
}
}
question from:https://stackoverflow.com/questions/65872085/multiply-elements-in-an-array-in-specific-positions-the-first-element-with-the

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to iterate the array from the beginning (i=0) and the end (j=array.length-1) and multiply the items at these indices as follows:

int [] array = new int [] {1, 1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0, j = array.length-1; i <= j; i++, j--) {
    sum += array[i] * array[j];
}
System.out.println(sum); //15

In case of an odd number of items and you want to count the middle once without multiplying it by itself (use above solution if not):

int [] array = new int [] {1, 1, 2, 2, 3, 4, 5};
int sum = 0;
for (int i = 0, j = array.length-1; i <= j; i++, j--) {
    sum += (i!=j) ? array[i] * array[j] : array[i];
}
System.out.println(sum); //17

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...