src: https://leetcode.com/problems/string-to-integer-atoi/
Implement
atoi
to convert a string to an integer.
实现atoi,即字符串转为整数。
分析:该问题评级为Easy,但是在leetcode平台上通过率仅为13.8%,所以通过率不亚于评级为Hard的题目,主要原因在于对各种情况的考虑,从另一角度讲,这道题目对测试的要求较高。
其中需要注意的有以下几点:
1.输入字符串长度为0时;
2.输入字符串前后有空格的时候,要先处理空格;
3.输入字符串长度为1的时候,返回该字符对应的数字,如果是非数字字符,那么返回0;
4.输入字符带有“+”或者“-”号的时候,如果第二个字符不为数字,则为非法数字,返回0;
5.当以上输入全部合法,那么要考虑输入字符串转换为int类型的时候是否在区间[ -2147483648, 2147483647]中;
6.当输入字符串中有非法字符时,那么要从第一个字符起,截取最长字符串为合法数字,然后转换;
其中需要注意的有以下几点:
1.输入字符串长度为0时;
2.输入字符串前后有空格的时候,要先处理空格;
3.输入字符串长度为1的时候,返回该字符对应的数字,如果是非数字字符,那么返回0;
4.输入字符带有“+”或者“-”号的时候,如果第二个字符不为数字,则为非法数字,返回0;
5.当以上输入全部合法,那么要考虑输入字符串转换为int类型的时候是否在区间[ -2147483648, 2147483647]中;
6.当输入字符串中有非法字符时,那么要从第一个字符起,截取最长字符串为合法数字,然后转换;
public class StringtoInteger {
public int myAtoi(String str) {
if (str == null)
return 0;
str = str.trim();
if (str.equals("") || str.equals("+") || str.equals("-"))
return 0;
if (str.length() == 1){
if (str.charAt(0) >= '0' && str.charAt(0) <= '9')
return str.charAt(0) - '0';
else
return 0;
}
if (str.length() > 1 && (str.charAt(0) == '+' || str.charAt(0) == '-')){
if (str.charAt(1) < '0' || str.charAt(1) > '9')
return 0;
}else if (str.length() > 1 && (str.charAt(0) < '0' || str.charAt(0) > '9')){
return 0;
}
if (str.length() > 1 && (str.charAt(1) == '+' || str.charAt(1) == '-'))
return 0;
str = maxLengthInteger(str);
if (str.charAt(0) == '-'){
if (str.length() > 11){
return -2147483648;
}
if (str.length() == 11 && str.compareTo("-2147483648") > 0){
return -2147483648;
}
return Integer.parseInt(str);
}else if (str.charAt(0) == '+'){
if (str.length() > 11){
return 2147483647;
}
if (str.length() == 11 && str.compareTo("+2147483647") > 0){
return 2147483647;
}
return Integer.parseInt(str.substring(1));
}else {
if (str.length() > 10)
return 2147483647;
if (str.length() == 10 && str.compareTo("2147483647") > 0)
return 2147483647;
return Integer.parseInt(str);
}
}
public String maxLengthInteger(String str){
int k = 0;
if (str.charAt(0) == '-' || str.charAt(0) == '+'){
k = 1;
while(true) {
if (k > str.length() - 1 || (str.charAt(k) < '0' || str.charAt(k) > '9')) {
k--;
break;
}
else
k++;
}
}else{
while(true) {
if (k > str.length() - 1 || (str.charAt(k) < '0' || str.charAt(k) > '9')) {
k--;
break;
}
else
k++;
}
}
return str.substring(0, k + 1);
}
}