Clamp a Value into a Range
Problem
Read three integers: value, low and high (low <= high). Print the value if it is inside [low, high]. Print low if the value is smaller and high if it is larger.
Constraints
- |value| <= 10^12
- low <= high
Examples
Input
5 1 10
Output
5
Input
-3 0 4
Output
0
Solutions
Clamping keeps a value inside a range. The usual way is Math.min(Math.max(value, low), high). Make sure low is not above high.
/*
* Problem : Clamp a value.
* Input : Three integers: value, minimum, maximum.
* Output : The clamped value.
* Approach: min and max.
* 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: If the value is below the minimum, use the minimum. If it is above the maximum, use the maximum.
return Math.min(Math.max(a, b), m);
}
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 (1)
- What if the value is below the minimum?