From 57a165bba03cec32c0d901322e05d8fa4bd52698 Mon Sep 17 00:00:00 2001 From: Jayana Anjani Pavan Vardhan Naidu Date: Wed, 26 Nov 2025 19:59:52 +0530 Subject: [PATCH] refactor: improve Floor method to handle edge cases - Add edge case handling for NaN, Infinity, and out-of-bounds values - Improve consistency with Ceil.java implementation - Add handling for positive numbers between 0 and 1 - Update Javadoc to match Ceil.java format and clarity - Use long cast to handle larger numbers correctly --- .../java/com/thealgorithms/maths/Floor.java | 27 ++++++++++++------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/thealgorithms/maths/Floor.java b/src/main/java/com/thealgorithms/maths/Floor.java index 271fc42d0d17..61fa0113d10a 100644 --- a/src/main/java/com/thealgorithms/maths/Floor.java +++ b/src/main/java/com/thealgorithms/maths/Floor.java @@ -1,24 +1,33 @@ package com.thealgorithms.maths; +/** + * Utility class to compute the floor of a given number. + */ public final class Floor { - private Floor() { } /** - * Returns the largest (closest to positive infinity) + * Returns the largest double value that is less than or equal to the input. + * Equivalent to mathematical ⌊x⌋ (floor function). * - * @param number the number - * @return the largest (closest to positive infinity) of given - * {@code number} + * @param number the number to floor + * @return the largest double less than or equal to {@code number} */ public static double floor(double number) { - if (number - (int) number == 0) { + if (Double.isNaN(number) || Double.isInfinite(number) || number == 0.0 || number < Integer.MIN_VALUE || number > Integer.MAX_VALUE) { return number; - } else if (number - (int) number > 0) { - return (int) number; + } + + if (number > 0.0 && number < 1.0) { + return 0.0; + } + + long intPart = (long) number; + if (number < 0 && number != intPart) { + return intPart - 1.0; } else { - return (int) number - 1; + return intPart; } } }