We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int []arr = new int[n];
for(int i = 0; i<n; i++){
arr[i] = sc.nextInt();
}
System.out.format("%.1f\n", mean(arr, n));
System.out.format("%.1f\n",median(arr, n));
System.out.println(mode(arr, n));
}
public static double mean(int arr[], int n){
long sum = 0;
for(int i = 0; i<n; i++){
sum += arr[i];
}
double ans = (double) sum / (long)n;
return ans;
}
public static double median(int arr[], int n){
Arrays.sort(arr);
int mid = n/2;
double ans;
if(n%2 == 0){
ans = (((double)arr[mid] + (double)arr[mid-1])/2);
}
else{
ans = (arr[mid]);
}
return ans;
}
public static int mode(int arr[], int n){
Arrays.sort(arr);
int mode = 0;
int c = 0;
int res = 0;
for(int i =0; i < n-1 ; i++){
int count =0;
for(int j=1; j < n; j++){
if(arr[i]==arr[j]){
count++;
c = arr[i];
}
if(mode<=count){
mode = count;
res =c;
}
else{
continue;
}
}
}
if(mode>1) return res;
else return arr[0];
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 0: Mean, Median, and Mode
You are viewing a single comment's thread. Return to all comments →
import java.io.; import java.util.; import java.text.; import java.math.; import java.util.regex.*;
public class Solution {
}