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.
思路:
1. Skipping all leading whitespaces
2. positive or negative
3. number might overflow
4. empty string or null string
代码一和代码二思路一样,代码二更简洁。代码一是我自己写的代码,代码二来自the most voting in LeetCode discussion part
代码一:
public int myAtoi(String str) {
if (str == null || str.length() == 0){
return 0;
}
int sum = 0;
int index = 0;
while (index < str.length() && str.charAt(index) == ' '){
index++;
}
int sign = 1;
if (str.charAt(index) == '-' || str.charAt(index) == '+'){
sign = str.charAt(index) == '-' ? -1 : 1;
index++;
}
for (int i = index; i < str.length() && Character.isDigit(str.charAt(i)); i++){
if (sum > Integer.MAX_VALUE / 10 || (sum == Integer.MAX_VALUE /10 && str.charAt(i) - '0' > 7)){
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; // handle overflow
}
sum = sum * 10 + (str.charAt(i) - '0');
}
return sum * sign;
}
代码二:
public int myAtoi(String str) {
if (str == null || str.length() == 0){
return 0;
}
int sum = 0, sign = 1, i = 0;
while (i < str.length() && str.charAt(i) == ' '){
i++;
}
if (str.charAt(i) == '-' || str.charAt(i) == '+'){
sign = str.charAt(i) == '-' ? -1 : 1;
i++;
}
while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'){
if (sum > Integer.MAX_VALUE / 10 || (sum == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)){
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
sum = sum * 10 + (str.charAt(i) - '0');
i++;
}
return sum * sign;
}