19. Nearest Multiple of 10

The problem can be found at the following link: Question Link

Problem Description

Given a string str representing a positive number, the task is to round str to the nearest multiple of 10. If two multiples are equally close to str, choose the smallest one.

Example:

Input: str = "29" Output: "30"

Explanation: The close multiples are 20 and 30, and 30 is the nearest to 29.

Input: str = "15" Output: "10"

Explanation: 10 and 20 are equally distant from 15. The smallest of the two is 10.

My Approach

  1. Check the Length of the Input String:

    • If the string is empty, return it immediately.

  2. Extract the Last Digit:

    • Convert the last character of the string to an integer to determine how to round.

  3. Round to the Nearest Multiple of 10:

    • If the last digit is less than or equal to 5, change the last digit to '0'.

    • If the last digit is greater than 5, change the last digit to '0' and carry over the increment to the preceding digits, handling any cascading carries (e.g., from 9 to 0).

  4. Return the Result:

    • If a carry occurs past the first digit, prepend '1' to the string.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), where n is the length of the input string, as we traverse the string to perform operations based on its length.

  • Expected Auxiliary Space Complexity: O(1), as we use a constant amount of additional space for variables.

Code (C++)

Code (Java)

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, please visit my LinkedIn: Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.

⭐ Star this repository if you find it helpful or intriguing! ⭐


📍Visitor Count

Last updated