题设
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.
要点
- 可以用上一题的方式判断是否溢出
- 可以用Double存储,与Integer.Max和Min比较判断是否溢出
- 一系列的边界条件需要不断去试
字符串转int无非就是做一遍遍历,但是这个题目的要求和atoi有很多不一样的地方(特别是不合格的返回0而不是-1)。。不看提示肯定会跪的。
具体要求有:
1、字符串为空,返回0;
2、正负号只取一个;
3、string除了数字还可能出现别的字符。如果遇到非数字,则只取其之前的作为结果;
4、取完正负号后,如果接下来又是非数字,无效,返回0;
5、如果超出int的范围(-2147483648--->2147483647),则返回最大、最小边界。
public static int myAtoi(String str){
if(str.length() == 0 || str == null) // 空字符串,返回0
return 0;
str = str.trim(); // 去除首尾的空格
boolean isNagative = false; // 是否是负数
int begin = 0; // 从哪个位置开始进行数字转换
if(str.charAt(0) == '-') { // 负数
isNagative = true;
begin++;
}
else if(str.charAt(0) == '+') { // 正数
isNagative = false;
begin++;
}
else{
if(str.charAt(0) < '0' || str.charAt(0) > '9') { // 第一位不是+-号,也不是数字,返回0
return 0;
}
begin = 0;
}
double sum = 0; // 为了防止溢出,用double,这样可以和Int的最大、最小值比较
for(; begin < str.length();begin++){
if(str.charAt(begin) < '0' || str.charAt(begin) > '9') // 非法字符,转化完成
break;
else{
sum *= 10;
int digit = Integer.parseInt(String.valueOf(str.charAt(begin))); // 累计数字大小
sum += digit;
}
}
if(isNagative == true) // 负数
sum *= -1;
if(sum > Integer.MAX_VALUE) // 边界判断,超出Integer边界就返回边界
return Integer.MAX_VALUE;
if(sum < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int)sum;
}
网友评论