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.
spoilers alert... click to show 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.
虽然atoi的算法很简单,但是要考虑清楚各种可能出现的情况,以上是java代码。
public int atoi(String str){
String temp=str.trim();
int MIN_VALUE=Integer.MIN_VALUE;
int MAX_VALUE=Integer.MAX_VALUE;
int sum=0;
int flag=1;
if(temp.length()==0)
return 0;
if(temp.charAt(0)=='+'){
flag=1;
temp=temp.substring(1);
}
else if(temp.charAt(0)=='-'){
flag=-1;
temp=temp.substring(1);
}
for(int i=0;i<temp.length();i++){
char c=temp.charAt(i);
int d=c-'0';
if(d<0||d>9){
break;
}else{
if(sum>MAX_VALUE/10){
if(flag>0)
return MAX_VALUE;
else
return MIN_VALUE;
}
sum*=10;
if(flag<0&&sum-1>MAX_VALUE-d)
return MIN_VALUE;
else if(flag>0&&sum>MAX_VALUE-d)
return MAX_VALUE;
else
sum+=d;
}
}
return sum*flag;
}
c++的:
int matoi(const char *str){
if(strlen(str)==0)
return 0;
int flag=1;
int index=0;
while(str[index]==' ')
index++;
if(str[index]=='+')
index++;
else if(str[index]=='-'){
index++;
flag=-1;
}
int sum=0;
while(true){
char c=str[index++];
int d=c-'0';
if(d<0||d>9)
break;
if(sum>INT_MAX/10){
if(flag>0)
return INT_MAX;
else
return INT_MIN;
}
sum*=10;
if(sum>INT_MAX-d){
if(flag>0)
return INT_MAX;
else{
if(sum>INT_MAX-d+1)
return INT_MIN;
}
}
sum+=d;
}
return sum*flag;
}