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.
spoilers alert... click to show requirements for atoi.
publicclassSolution {publicintmyAtoi(String str) {
// trime leading and tailing spaces
str = str.trim();
// if the lenght of stri is 0 or the first character of str is not reasonable, return 0 directlyif (str.length() == 0){
return0;
}
int begin = 0; // the index of first digitint sign = 1; // the sign of the number. 1 represent the number is positive, or negative if (str.charAt(0) == '-'){
sign = -1;
begin = 1;
} elseif (str.charAt(0) == '+'){
begin = 1;
}
long sum = 0; // handle integer overflowfor (int i = begin; i < str.length(); i++){
char ch = str.charAt(i);
if (ch < '0' || ch > '9'){ // if the ch is not reasonable char, break the loopbreak;
}
sum = 10 * sum + (ch - '0');
if (sum > Integer.MAX_VALUE){
break;
}
}
sum = sign == 1 ? sum : -sum;
if (sum > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
} elseif (sum < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
return (int)sum;
}
}