Leetcode 8. String to Integer (atoi)
The problem “String to Integer (atoi)” requires us to implement a function that converts a string to a 32-bit signed integer (similar to the C/C++ atoi
function).
The function should handle the following cases:
The range for 32-bit signed integer is [-2³¹, 2³¹ − 1] which translates to [-2147483648, 2147483647].
Integer.MAX_VALUE
or Integer.MIN_VALUE
accordingly)public class Solution {
public int myAtoi(String s) {
// Step 1: Trim whitespaces
s = s.trim();
if (s.isEmpty()) return 0;
// Step 2: Handle sign
int sign = 1;
int startIndex = 0;
if (s.charAt(0) == '-') {
sign = -1;
startIndex = 1;
} else if (s.charAt(0) == '+') {
startIndex = 1;
}
// Step 3: Convert digits to number
long result = 0;
for (int i = startIndex; i < s.length(); i++) {
char c = s.charAt(i);
if (!Character.isDigit(c)) break;
result = result * 10 + (c - '0');
// Step 4: Check overflow and underflow conditions
if (sign * result < Integer.MIN_VALUE) return Integer.MIN_VALUE;
if (sign * result > Integer.MAX_VALUE) return Integer.MAX_VALUE;
}
return (int)(sign * result);
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example tests
System.out.println(solution.myAtoi("42")); // Output: 42
System.out.println(solution.myAtoi(" -42")); // Output: -42
System.out.println(solution.myAtoi("4193 with words")); // Output: 4193
System.out.println(solution.myAtoi("words and 987")); // Output: 0
System.out.println(solution.myAtoi("-91283472332")); // Output: -2147483648 (Integer.MIN_VALUE)
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?