Median of Three Numbers
Problem
Print the middle one of three numbers (the one that is neither the smallest nor the biggest). If two numbers are equal, the middle value is still printed once.
Constraints
- |value| <= 10^9
Examples
Input
2 3 1
Output
2
Solutions
The three numbers are the smallest, the middle and the biggest. If we remove the first and last from the total, only the middle is left. This works with equal numbers too.
/*
* Problem : Median of three.
* Input : Three integers.
* Output : The middle one.
* Approach: Total minus extremes.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(long a, long b, long m) {
// Step 1: Add all three, then take away the biggest and the smallest. The rest is the middle number.
long biggest = Math.max(a, Math.max(b, m));
long smallest = Math.min(a, Math.min(b, m));
return a + b + m - biggest - smallest;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long a = scanner.nextLong();
long b = scanner.nextLong();
long m = scanner.nextLong();
System.out.println(solve(a, b, m));
}
}
Hints (2)
- What is left after removing both extremes?
- Does it work if two numbers are equal?