JavaAlgorithms/Maths/AbsoluteMin.java

36 lines
917 B
Java
Raw Normal View History

2019-10-07 19:49:06 +08:00
package Maths;
import java.util.Arrays;
/**
* description:
* <p>
* absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2
* </p>
*/
public class AbsoluteMin {
public static void main(String[] args) {
2020-08-16 22:46:39 +08:00
int[] testnums = new int[]{4, 0, 16};
assert absMin(testnums) == 0;
2019-10-07 19:49:06 +08:00
int[] numbers = new int[]{3, -10, -2};
System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers));
}
/**
2019-12-11 12:35:54 +08:00
* get the value, returns the absolute min value min
2019-10-07 19:49:06 +08:00
*
* @param numbers contains elements
* @return the absolute min value
*/
public static int absMin(int[] numbers) {
int absMinValue = numbers[0];
for (int i = 1, length = numbers.length; i < length; ++i) {
if (Math.abs(numbers[i]) < Math.abs(absMinValue)) {
absMinValue = numbers[i];
}
}
return absMinValue;
}
}