String to Integer (atoi) Medium
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.
spoilers alert... click to show requirements for atoi.
Requirements for atoi:
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 int myAtoi(String str) {
if (str == null || str.length() == 0)
return 0;
long num = 0;
int cur = 0;
int sign = 1;
str = str.trim();
if (str.length() == 0)
return 0;
char first = str.charAt(cur);
if (first == '-') {
sign = -1;
++cur;
} else if (first == '+')
++cur;
while (cur < str.length()) {
char cc = str.charAt(cur++);
if (!Character.isDigit(cc)) {
return (int) num * sign;
}
num = num * 10 + (cc - '0');
if (sign > 0 && num * sign > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (sign < 0 && num * sign < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
}
return (int) num * sign;
}
思路:考虑正负和溢出,从前到后逐一扫转即可。奇技淫巧:转成char后和’0’的差值即是该位数值
本文详细解析了StringtoInteger(atoi)的实现过程,包括处理正负号、数字字符转换、溢出检查等关键步骤。通过示例代码展示了如何将字符串安全地转换为整数,同时考虑到各种边界条件。
1632

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



