Java 8 style sum of long type array elements

You are given an array of N integers of size . You need to print the sum of the elements in the array, keeping in mind that some of those integers may be quite large.

Input Format
The first line of the input consists of an integer N. The next line contains N space-separated integers contained in the array.

Output Format
Print a single value equal to the sum of the elements in the array.

Sample Input
5
1000000001  1000000002  1000000003  1000000004  1000000005

Note:
The range of the 32-bit integer is – 2,147,483,648 to 2,147,483,647(inclusive).
When we add several integer values, the resulting sum might exceed the above range. You might need to use long data type in Java to store such sums.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static long aVeryBigSum(int n, long[] ar) {
        Arrays.stream(ar).sum();// That's it, so easy with streams API of JAVA 8
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        long[] ar = new long[n];
        for(int ar_i = 0; ar_i < n; ar_i++){
            ar[ar_i] = in.nextLong();
        }
        long result = aVeryBigSum(n, ar);
        System.out.println(result);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *