题目描述
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.
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.
把字符串变成整数,超出范围的用最大值表示。最开始可以有空格,但不能有其他字符;后面可以有无效字符。
解题思路
用一个 boolean 标记是否已经开始数值计算,用 positive 存储'+/-'。用 long 存储返回值,一旦返回值超出范围,就返回最大值。
代码
class Solution {
public int myAtoi(String str) {
if (str == null || str.trim().length() == 0)
return 0;
str = str.trim();
long ret = 0;
boolean label = false;
long positive = 1;
for (int i = 0; i < str.length(); i++) {
if (!label && (str.charAt(i) == '-' || str.charAt(i) == '+' || (str.charAt(i) >= '0' && str.charAt(i) <= '9'))) {
if (str.charAt(i) == '-')
positive = -1;
if (str.charAt(i) >= '0' && str.charAt(i) <= '9')
ret = ret + str.charAt(i) - '0';
label = true;
} else if (label && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
ret *= 10;
ret = ret + str.charAt(i) - '0';
} else if (str.charAt(i) < '0' || str.charAt(i) > '9') {
break;
}
if (ret * positive > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (ret * positive < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
}
ret *= positive;
return (int)ret;
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于