8. String to Integer (atoi)
Explanation:
To solve this problem, we need to follow the steps outlined in the problem description: ignoring leading whitespace, determining sign, converting the integer, and handling rounding. We can achieve this by iterating over the characters in the string and updating our result accordingly.
- Trim leading whitespace.
- Determine sign.
- Convert the integer value.
- Handle rounding for out-of-range values.
Time Complexity: O(n) where n is the length of the input string. Space Complexity: O(1)
:
class Solution {
public int myAtoi(String s) {
if (s.isEmpty()) return 0;
int i = 0, sign = 1, result = 0;
while (i < s.length() && s.charAt(i) == ' ') {
i++;
}
if (i < s.length() && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
sign = (s.charAt(i) == '-') ? -1 : 1;
i++;
}
while (i < s.length() && Character.isDigit(s.charAt(i))) {
int digit = s.charAt(i) - '0';
if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10)) {
return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
result = result * 10 + digit;
i++;
}
return result * sign;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.