A string str is given to represent a positive number. The task is to round str to the nearest multiple of 10. If you have two multiples equally apart from str, choose the smallest element among them.
Examples:
Input: str = 29
Output: 30
Explanation: 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 multiples from 20. The smallest of the two is 10.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(1).
Constraints:
1 <= str.size()<= 105
Approach 01:
-
C++
-
Python
class Solution { public: string roundToNearest(string numberString) { int length = numberString.size(); int carry = 0; if (numberString[length - 1] <= '5') { numberString[length - 1] = '0'; return numberString; } else { numberString[length - 1] = '0'; for (int i = length - 2; i >= 0; i--) { if (numberString[i] == '9') { numberString[i] = '0'; carry = 1; } else { numberString[i]++; carry = 0; break; } } } if (carry == 1) { numberString = '1' + numberString; } return numberString; } };
class Solution: def roundToNearest (self, numberString) : length = len(numberString) carry = 0 if numberString[length - 1] <= '5': numberString = numberString[:-1] + '0' return numberString else: numberString = numberString[:-1] + '0' for i in range(length - 2, -1, -1): if numberString[i] == '9': numberString = numberString[:i] + '0' + numberString[i + 1:] carry = 1 else: numberString = numberString[:i] + chr(ord(numberString[i]) + 1) + numberString[i + 1:] carry = 0 break if carry == 1: numberString = '1' + numberString return numberString
Time Complexity
- Length Calculation:
The function first calculates the length of the input string, which takes \(O(1)\).
- Rounding Logic:
The function checks the last digit and may need to traverse back through the string to handle the carry. In the worst case, if every digit is ‘9’, it will traverse the entire string, resulting in \(O(n)\) time complexity, where \(n\) is the length of the input string.
- Overall Time Complexity:
The overall time complexity is \(O(n)\).
Space Complexity
- Auxiliary Space:
The function modifies the input string in place and does not use any additional data structures that grow with input size. Therefore, the auxiliary space complexity is \(O(1)\).
- Overall Space Complexity:
The overall space complexity is \(O(1)\).