8. String to Integer (atoi)
Asked at 19Bloomberg62Meta57Amazon55Microsoft52Google44Apple43Cadence100Niantic100Valve90Netflix69Adobe63Qualcomm58Nvidia55Expedia54Uber52Accenture44tcs42Goldman Sachs40Databricks37
Problem
Implement myAtoi(s): skip leading spaces, read an optional + or -, then read digits until the first non-digit (leading zeros are fine). No digits gives 0. Clamp the result to the 32-bit signed range [−2³¹, 2³¹ − 1].
Example: "42" → 42; " -042" → -42; "1337c0d3" → 1337; "words 987" → 0
Skip spaces, read an optional sign, read digits until a non-digit; clamp to [−2³¹, 2³¹−1] (check before multiplying in Java).
Complexity: O(n).
class Solution:
def myAtoi(self, s: str) -> int:
i, n = 0, len(s)
while i < n and s[i] == " ":
i += 1
sign = 1
if i < n and s[i] in "+-":
sign = -1 if s[i] == "-" else 1
i += 1
num = 0
while i < n and s[i].isdigit():
num = num * 10 + int(s[i])
i += 1
return max(-2 ** 31, min(2 ** 31 - 1, sign * num))
assert Solution().myAtoi("42") == 42
assert Solution().myAtoi(" -042") == -42
assert Solution().myAtoi("1337c0d3") == 1337
assert Solution().myAtoi("0-1") == 0
assert Solution().myAtoi("-91283472332") == -2147483648
class Solution {
public int myAtoi(String s) {
int i = 0, n = s.length(), sign = 1, num = 0;
while (i < n && s.charAt(i) == ' ') i++;
if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) sign = s.charAt(i++) == '-' ? -1 : 1;
while (i < n && Character.isDigit(s.charAt(i))) {
int d = s.charAt(i++) - '0';
if (num > (Integer.MAX_VALUE - d) / 10) return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
num = num * 10 + d;
}
return sign * num;
}
}
func myAtoi(s string) int {
i, n := 0, len(s)
for i < n && s[i] == ' ' {
i++
}
sign := 1
if i < n && (s[i] == '+' || s[i] == '-') {
if s[i] == '-' {
sign = -1
}
i++
}
num := 0
for ; i < n && s[i] >= '0' && s[i] <= '9'; i++ {
num = num*10 + int(s[i]-'0')
if num > math.MaxInt32+1 { // already out of range: stop before int64 overflows too
break
}
}
return max(math.MinInt32, min(math.MaxInt32, sign*num))
}