Description
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.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
public int myAtoi ( String str ) {
if ( str.length() <= 0 ){
return 0;
}
str = str.trim();
boolean flag = true;
int start = 0, end = str.length()-1;
long answer = 0;
if ( str.charAt(0)=='-' && str.length()>1){
flag = false;
start ++;
} else if ( str.charAt(0)=='+' && str.length()>1){
start ++;
}
for ( int i=start; i<=end; i++ ){
if ( str.charAt(i) >= '0' && str.charAt(i) <= '9' ) {
answer = answer * 10 + ( str.charAt(i) - '0' );
}
else{
break;
}
if( answer > Integer.MAX_VALUE){
break;
}
}
answer = flag == true ? answer : (-1)*answer;
if ( answer > Integer.MAX_VALUE ){
return Integer.MAX_VALUE;
}else if( answer<Integer.MIN_VALUE ){
return Integer.MIN_VALUE;
}else {
return (int)answer;
}
}
many string cases we need to be care.
- ""
-
-
- " 123"
- " +234"
string bigger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE or long type value.
so, when we calculate new answer value, then judge if the new answer value is bigger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE. if that, break and do the flowing works.
来源:oschina
链接:https://my.oschina.net/u/1447519/blog/1564046