8. String to Integer (atoi)¶
Intuition¶
We need to convert a string to a valid 32-bit signed integer. However, we have to carefully follow the steps:
- Trim whitespace
- Determine the sign
- Parse digits until a non-digit is encountered
- Clamp the result within the integer bounds
This is basically a manual parser that mimics what standard functions like atoi() do in C/C++.
Complexity¶
| Space Complexity | Time Complexity |
|---|---|
| $\(\text{O}(1)\)$ | $\(\text{O}(N)\)$ |
Code¶
public int myAtoi(String inputString) {
// Step 1: Trim whitespace
inputString = inputString.trim();
// Initialize pointer and accumulator
int index = 0;
long numericValue = 0;
// Edge case: Empty string
if (inputString.length() == 0) return 0;
// Step 2: Check for optional sign
boolean isNegative = (inputString.charAt(index) == '-');
if (inputString.charAt(index) == '-' || inputString.charAt(index) == '+') {
index++;
}
// Step 3: Parse digits
while (index < inputString.length()) {
char currentChar = inputString.charAt(index);
// Stop at first non-digit
if (!Character.isDigit(currentChar)) break;
// Build the number one digit at a time
numericValue = numericValue * 10 + (currentChar - '0');
// Step 4: Clamp if overflow occurs
if (numericValue > Integer.MAX_VALUE) {
return isNegative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
index++;
}
// Step 5: Apply sign
numericValue = isNegative ? -numericValue : numericValue;
return (int) numericValue;
}