This code implements a function called roundToNearest
that rounds a given number (represented as a string) to the nearest multiple of 10. Here's a summary and step-by-step explanation:
Summary:
The function takes a string representation of a number and rounds it to the nearest multiple of 10. If the last digit is 5 or less, it rounds down; otherwise, it rounds up. The function handles cases where rounding up causes carry-over to higher digits.
Step-by-step explanation:
-
Input validation:
- Check if the input string is null or empty. If so, throw an IllegalArgumentException.
-
Rounding down:
- If the last digit is '5' or less, replace it with '0' and return the result.
-
Rounding up:
- If the last digit is greater than '5', the function proceeds to round up.
-
Initialization:
- Convert the input string to a character array.
- Set the last digit to '0'.
- Initialize a boolean
toAdd
to true, which indicates if we need to carry over to the next digit.
-
Rounding process:
- Iterate through the digits from right to left (excluding the last digit).
- If
toAdd
is false, break the loop (no more carry-over needed). - If the current digit is '9':
- Set it to '0'.
- Keep
toAdd
as true (continue carry-over).
- If the current digit is not '9':
- Increment the digit.
- Set
toAdd
to false (no more carry-over needed).
-
Handling overflow:
- After the loop, if
toAdd
is still true, it means we need to add a new leading digit '1'.
- After the loop, if
-
Result formation:
- Combine the prefix (if any) with the modified character array.
- Return the result as a string.
The code handles various cases, including numbers that require multiple carry-overs (like 999 rounding to 1000) and ensures correct rounding for all input values.
Top comments (0)