Monday, June 29, 2015

A Very Big Sum

Problem Statement
You are given an array of integers of size N. You need to print the sum of the elements of the array.
Note: A signed 32bit integer value uses 1st bit to represent the sign of the number and remaining 31bits to represent the magnitude. The range of the 32bit integer is 231 to 2311 or [2147483648,2147483647]. When we add several integer values, the resulting sum might exceed this range. You might need to use long long int in C/C++ or long data type in Java to store such sums.
Input Format
The first line of the input consists of an integer N. The next lines contain N space separated integers describing the array.
Constraints
1N10
0A[i]1010
Output Format
Output a single value equal to the sum of the elements of the array.
Sample Input
5
1000000001 1000000002 1000000003 1000000004 1000000005
Sample Output
5000000015

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

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        long bi=0;
        int arr[] = new int[n];
        for(int i=0; i < n; i++){
            arr[i] = in.nextInt();
        }
        for(int m:arr){
            bi+=m;
        }
        System.out.println(bi);
    }
}



1 comment:

  1. import java.util.Scanner;
    class Test{
    public static void main(String args[]){
    Scanner scanner = new Scanner(System.in);
    int n=scanner.nextInt();
    int[] array = new int[n];

    long sum = 0;

    for (int i=0; i<n; i++)
    {
    array[i] = scanner.nextInt();
    }
    for( int num : array) {
    sum = sum+num;
    }
    System.out.println(sum);
    }
    }

    ReplyDelete