Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
public class Solution {
public int atoi(String s) {
s = s.trim();
long value = 0;
boolean isPositive = true;
for (int i = 0; i < s.length(); i++) {
if (i == 0 && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
if (s.charAt(i) == '-') {
isPositive = false;
}
continue;
}
if (s.charAt(i) < '0' || s.charAt(i) > '9') break;
value = 10 * value + s.charAt(i) - '0';
}
value = isPositive == true ? value : value * -1;
if (value < -2147483648) {
return -2147483648;
} else if (value > 2147483647) {
return 2147483647;
} else {
return (int) value;
}
}
}
本文详细解析了atoi函数的实现原理,包括如何处理空格、正负号、数字字符以及溢出检查,提供了深入理解字符串转整数过程的指南。
2688

被折叠的 条评论
为什么被折叠?



