題目描述
給定一個大小為N的整數陣列,您可以找出所有元素的和嗎?
原題網址
輸入格式
第一行包含一個整數N,接下來的一行有N個整數,使用空格進行分隔,每個整數分別表示陣列的一個元素。
輸出格式
輸出陣列中所有元素相加的結果。
範例輸入
6
1 2 3 4 10 11
範例輸出
31
額外解釋
1 + 2 + 3 + 4 + 10 + 11 = 31
解題概念
先從標準輸入中讀取陣列的長度和陣列的元素,建立出整數陣列物件,接著再使用Java 8提供的串流(Stream)功能,把陣列轉成串流物件後,直接使用「sum」方法來計算總和。
參考答案
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
public static void main(final String[] args) throws Exception {
final Scanner sc = new Scanner(System.in);
final int n = sc.nextInt();
final int[] array = new int[n];
for (int i = 0; i < n; ++i) {
array[i] = sc.nextInt();
}
System.out.println(Arrays.stream(array).sum());
}
}