问题描述:
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.
分析:首先,先对字符串进行一次过滤,将开头的空格去掉。然后在查找之后的,当遇到+-时后面一定要求是数字,也即不能是++或者+-或者-+或者–等情况。此外,更重要的一点是注意溢出现象。特别的当sum*10时发生溢出不好判断,因此,我设置了sum的阈值。当sum>这个阈值时,肯定会发生溢出。此时,再单独处理。
代码如下:404ms
public int myAtoi(String str) {
char tmp;
int sum = 0;
int i;
boolean minus = false;
boolean requireNumber = false;
boolean overflow = false;
//clear the space
for(i = 0;i<str.length();i++){
if((tmp=str.charAt(i))!=' ')
break;
}
for(;i<str.length();i++){
if((tmp=str.charAt(i))=='+'){
if(requireNumber)
break;
requireNumber = true;
}
else if(tmp=='-'){
if(requireNumber)
break;
requireNumber = true;
minus = true;
}
else if(tmp>='0'&&tmp<='9'){
if(sum>Integer.MAX_VALUE/10){
sum = -1;
}else
sum = sum*10+tmp-'0';
if(sum<0){
sum = Integer.MAX_VALUE;
overflow = true;
}
}else {
break;
}
}
if(overflow&&minus)
return sum+1;
else if(overflow)
return sum;
return minus?-sum:sum;
}
本文介绍了一种将字符串转换为整数的有效方法。重点讨论了输入情况的处理,包括正负号、非数字字符及可能的整数溢出问题,并提供了一个具体的Java代码示例。

5389

被折叠的 条评论
为什么被折叠?



