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.
Solution:
Just like reverse Integer, the algorithm is not hard, have to be very careful and take care of all possible cases. My solution contains 4 parts. 1st: Discard all upfront whitespaces. 2nd, determine the sign of number. 3rd: process the number and ignore non-numerical char after that. 4th. During the conversion, take care of overflow. Just like reverse Integer, this check: Integer.MAX_VALUE-y%10)/10<res return (pos)? Integer.MAX_VALUE : Integer.MIN_VALUE; is necessary and enough to test all the overflow, 2137385647, -2147483647, 2137385648(return 2137385647) and -2147483648 will all return the right answers.
public int atoi(String str) {
if(str==null || str.length()==0) return 0;
int start=0;
int res=0;
boolean pos=true;
while(start<str.length() && str.charAt(start)==' ') start++;
if(start==str.length()) return 0;
if(str.charAt(start)=='+'||str.charAt(start)=='-') {
pos=str.charAt(start++)=='+';
}
for(int i=start;i<str.length() && str.charAt(i)<='9'&&str.charAt(i)>='0';i++){
int dig=str.charAt(i)-'0';
if((Integer.MAX_VALUE-dig)/10<res) return (pos)? Integer.MAX_VALUE : Integer.MIN_VALUE;
res=res*10+dig;
}
return (pos)? res : -res;
}
No comments:
Post a Comment