1 原题
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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
2 题目理解
这题的意思是,给定一个用String表示的数字,然后需要你转化为一个真正的int呢。
Leetcode标记的难度是Easy,但是我觉得这道题陷阱很多,要注意到很多很多特别的地方,我就这么提几个:
0、我做的时候给定的String一定是合法的数字,这点很重要,因为我往后刷遇到过类似问题,这边给定的是合法的,所以部分处理就很简单了,特别是空格。
1、注意前后的空格,输入的数字可能会留空,所以往前往后都需要去空格。
2、需要考虑正负号,这个是合法的
3、注意int的最大值和最小值的绝对值大小不一样,所以如果在计算的时候是暂时抛弃了符号,一位一位的前进的,需要特别注意这个问题。
4、注意不要溢出
总之流程就是:
1、去除空格
2、检查是否正反符号
3、转换数字整体,并时刻检查是否溢出,关于溢出的问题的解决,可以看我前面的博客,这里我选用了long解决
3 AC解 Java
public class Solution {
/**
* 倘若某个数超过了2147483647则会变为负数,反过来一样*/
public int myAtoi(String str) {
if(str.equals(""))
return 0;
char chars[]=str.toCharArray();
long result=0,maxs=Integer.MAX_VALUE,mins=-1*(long)Integer.MIN_VALUE;
int i=0,flag=1;
while(chars[i]==' '){
i++;
}
if(chars[i]=='-'){
flag=-1;
i++;
}
else if(chars[i]=='+'){
flag=1;
i++;
}
while(i<str.length()){
if(chars[i]==' ')
return (int)result*flag;
if( chars[i]>'9' || chars[i]<'0' )
return (int)result*flag;
result=result*10+(chars[i++]-'0');
if(flag==1 && result>maxs ){
return (int)maxs*flag;
}
if(flag==-1 && result>mins ){
return (int)mins*flag;
}
}
return (int)result*flag;
}
}