BASHA TECH

[HackerRank][Java] Simple Array 본문

Activity/Coding Test

[HackerRank][Java] Simple Array

Basha 2023. 4. 7. 14:17
728x90

import java.io.*;
import java.util.*;

class Result {

    /*
     * Complete the 'simpleArraySum' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts INTEGER_ARRAY ar as parameter.
     */

    public static int simpleArraySum(List<Integer> ar) {
	// Write your code here
		int sum = 0;
        for (int i = 0; i < ar.size(); i++) {
            sum += ar.get(i); // Add each element of the list to the sum variable
        }
        return sum; // Return the sum of the elements in the list
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int arCount = Integer.parseInt(bufferedReader.readLine().trim()); // Read the number of elements in the array

        String[] arTemp = bufferedReader.readLine().replaceAll("\\s+$", "").split(" "); // Read the array elements as strings and split them by space

        List<Integer> ar = new ArrayList<>(); // Create a new ArrayList to store the array elements

        for (int i = 0; i < arCount; i++) {
            int arItem = Integer.parseInt(arTemp[i]); // Convert each string element to an integer
            ar.add(arItem); // Add the integer element to the ArrayList
        }

        int result = Result.simpleArraySum(ar); // Call the simpleArraySum method to find the sum of the elements in the ArrayList

        bufferedWriter.write(String.valueOf(result)); // Write the result to the output file
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

In this code, we read in an array of integers from the user as input and find the sum of its elements.

The Result class has a simpleArraySum method that takes a List of integers ar as an argument and returns the sum of its elements. We initialize a variable sum to 0 and loop through each element of the list using a for loop, adding each element to the sum variable. Finally, we return the value of sum. 

 

In the 'Solution' class, we read in the input from the user and convert it to a 'List' of integers called 'ar'. We then call the 'simpleArraySum' method on this list to find the sum of its elements, and write the result to an output file.

728x90
반응형
Comments