blog.itcode.devblog.itcode.dev

[Programmers / JAVA] Level 1 Calculating the Average (12944)

Complete the function solution that returns the average value of the array arr, which holds integers.

[Programmers / JAVA] Level 1 Calculating the Average (12944)

Complete the function solution that returns the average value of the array arr, which holds integers.
RWB0104
@RWBwritten at 2021-12-18 12:43:34
Programmers

시리즈 모아보기

Programmers

59 / 78
RankLanguage Used
Level 1

🖼️ JAVA

🔗 Calculating the Average

Complete the function solution that returns the average value of the array arr, which holds integers.

  • arr is an array with a length between 1 and 100, inclusive.
  • The elements of arr are integers between -10,000 and 10,000, inclusive.
arrreturn
{ 1, 2, 3, 4 }2.5
{ 5, 5 }5

We need to calculate and return the average of the elements in array arr. Using Stream, we can easily obtain it without a loop.

Arrays.stream(arr).sum() can be used to compute the total sum of the array elements in one go.

JAVA

import java.util.Arrays;

/**
 * Calculating the Average class
 *
 * @author RWB
 * @since 2021.12.13 Mon 21:49:40
 */
class Solution
{
	/**
	 * Method that returns the answer
	 *
	 * @param arr: [int[]] integer array
	 *
	 * @return [double] answer
	 */
	public double solution(int[] arr)
	{
		return (double) Arrays.stream(arr).sum() / arr.length;
	}
}
# Programmers# Algorithm# JAVA# Level 1
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08