We need to convert a string to a valid 32-bit signed integer. However, we have to carefully follow the steps:
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;
}