8. String to Integer (atoi)
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.
用String 里面的trim()去掉前后的空格, pos用来判断正负,如果出现非法字符第一位(+ - 0-9)其余(0-9)则直接break。
public class Solution {
public int myAtoi(String str) {
if(str == null) return 0;
str = str.trim();
int len = str.length();
if(len==0) return 0 ;
int pos = 1;//positive
int index = 0;
long res = 0 ;
int start = str.charAt(index);
if(start=='-'){
pos = -1;
index ++;
}else if(start =='+'){
pos = 1;
index ++;
}
for(int i =index ; i <len ; i++){
if(str.charAt(i)<'0' || str.charAt(i)>'9'){
break;
}
res = res*10 + (str.charAt(i) - '0');
if(res>Integer.MAX_VALUE && pos == 1) return Integer.MAX_VALUE ;
if(res>Integer.MAX_VALUE && pos == -1) return Integer.MIN_VALUE;
}
return (int) res*pos;
}
}