Implement Atoi
JavaView on GFG
Time: O(n)
Space: O(1)
Advertisement
Intuition
Parse integer from string: skip whitespace, handle sign, parse digits, clamp to INT range.
Algorithm
- 1Skip leading whitespace.
- 2Check sign (+ or -).
- 3Parse digits: result = result*10 + digit. Stop at non-digit.
- 4Clamp: if > INT_MAX return INT_MAX; if < INT_MIN return INT_MIN.
Common Pitfalls
- •Overflow during parsing: check before multiplying. Empty string or all-whitespace returns 0.
Implement Atoi.java
Java
// Approach: Handle leading spaces, optional sign, then parse digits. Handle overflow by clamping to INT bounds.
// Time: O(n) Space: O(1)
class Solution {
public int myAtoi(String s) {
int i = 0;
while (i < s.length() && s.charAt(i) == ' ') {
i++;
}
int sign = 1;
if (i < s.length() && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
if (s.charAt(i) == '-') {
sign = -1;
}
i++;
}
long result = 0;
while (i < s.length() && Character.isDigit(s.charAt(i))) {
result = result * 10 + (s.charAt(i) - '0');
if (result * sign > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (result * sign < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
i++;
}
return (int) (result * sign);
}
}
Advertisement
Was this solution helpful?