From c68f4ca860387ee3c7683ba4b731c16fb09f3834 Mon Sep 17 00:00:00 2001 From: shellhub Date: Mon, 7 Oct 2019 19:49:06 +0800 Subject: [PATCH] AbsoluteMax and AbsoluteMin --- Maths/AbsoluteMax.java | 32 ++++++++++++++++++++++++++++++++ Maths/AbsoluteMin.java | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 Maths/AbsoluteMax.java create mode 100644 Maths/AbsoluteMin.java diff --git a/Maths/AbsoluteMax.java b/Maths/AbsoluteMax.java new file mode 100644 index 00000000..18634bc3 --- /dev/null +++ b/Maths/AbsoluteMax.java @@ -0,0 +1,32 @@ +package Maths; + +import java.util.Arrays; + +/** + * description: + *

+ * absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10 + *

+ */ +public class AbsoluteMax { + public static void main(String[] args) { + int[] numbers = new int[]{3, -10, -2}; + System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers)); + } + + /** + * get the value, it's absolute value is max + * + * @param numbers contains elements + * @return the absolute max value + */ + public static int absMax(int[] numbers) { + int absMaxValue = numbers[0]; + for (int i = 1, length = numbers.length; i < length; ++i) { + if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) { + absMaxValue = numbers[i]; + } + } + return absMaxValue; + } +} diff --git a/Maths/AbsoluteMin.java b/Maths/AbsoluteMin.java new file mode 100644 index 00000000..4af43c5c --- /dev/null +++ b/Maths/AbsoluteMin.java @@ -0,0 +1,32 @@ +package Maths; + +import java.util.Arrays; + +/** + * description: + *

+ * absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2 + *

+ */ +public class AbsoluteMin { + public static void main(String[] args) { + int[] numbers = new int[]{3, -10, -2}; + System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers)); + } + + /** + * get the value, it's absolute value is min + * + * @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; + } +}