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.
Have you met this question in a real interview?
思路: 注意处理各种情况。处理顺序如下。
1. 前, 后面为空格
2. 首字母符号
3. 找到最后一位合法数字。
4. 长度是否超过10.
5. 从后往前, 每次乘10 相加
6. 注意检查超上下界。
7. 最后符号相乘。
public class Solution{
public int atoi(String str) {
// filter out all the whitespace characters until the first
// non-whitespace character is found
int start = 0;
str = str.trim();
// filter out the beginning 0s if it's not a 0
start = 0;
while (start < str.length() - 1 && str.charAt(start) == '0') {
start++;
}
str = str.substring(start);
// handle the empty string
if (str.length() == 0) {
return 0;
}
// truncate the sign
boolean negative = false;
if (str.charAt(0) == '-') {
negative = true;
str = str.substring(1);
} else if (str.charAt(0) == '+') {
str = str.substring(1);
}
// filter out all the characters after the first integral part
int end = 0;
while (end < str.length()) {
char c = str.charAt(end);
if ('0' <= c && '9' >= c) {
end++;
} else {
break;
}
}
str = str.substring(0, end);
// check if the string length is too long
if (str.length() > 10) {
if (negative)
return Integer.MIN_VALUE;
else
return Integer.MAX_VALUE;
}
// calculate the numeric value from the right to the left
int ret = 0;
int increment = 0;
int digit = 1;
for (int i = str.length() - 1; i >= 0; i--) {
char c = str.charAt(i);
increment = (str.charAt(i) - '0') * digit;
//Check the integer range.
if (!negative) {
// if out of the positive integer range
if (Integer.MAX_VALUE - ret - increment < 0) {
return Integer.MAX_VALUE;
}
} else {
// if out of the negative integer range
if (Integer.MIN_VALUE + ret + increment > 0) {
return Integer.MIN_VALUE;
}
}
ret += increment;
digit *= 10;
}
if (negative) {
ret *= -1;
}
return ret;
}
}