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.
思路
将注意力放在几个点上:
1. 前导空白字符
2. 符号
3. 是否溢出
4. 不合法的输入
略过前导空白字符后,也就是 ’ ’ ,判断第一个字符是否合法(是否为’+-‘或数字),若合法则确定整数符号。接着就是进行转换计算,在这期间可能会发生溢出和出现不合法字符,若出现溢出则返回最大/最小值,若出现不合法的字符,则马上返回已计算的结果,丢弃后面的字符。
使用C语言实现
Code
#include <math.h>
#define INT_MAX ( pow(2,sizeof(int)*8-1)-1 )
#define INT_MIN ( 0-pow(2,sizeof(int)*8) )
//min and max
int myAtoi(char* str) {
int sign=0;//sign, -1 minus, 1 plus
int opInt=0;//output integer
while(*str==' ')str++;//leading white-space
//what's the sign of integer?
//the first non-white-space character must be +- or digit
if(sign==0){
if(*str>='0'&&*str<='9'){
sign=1;//plus
//continue;
}else if(*str=='+'||*str=='-'){
sign=(*str=='+')?1:-1;//plus or minus
str++;//pointer move a step
}else{
return 0;//the first non-white-space character is invalid
}
}
while(*str!='\0'){
//conversion
//during the conversion, overflow may happen,non-digit character may show up
if(*str>='0'&&*str<='9'){
//overflow may happen
if( sign==1&&( opInt>INT_MAX/10||INT_MAX-opInt*10<*str-'0' )){//plus
return INT_MAX;
}
if( sign==-1&&( opInt>INT_MAX/10||INT_MAX-opInt*10+1<*str-'0' ) ){//minus
return INT_MIN;
}
opInt=opInt*10+(*str-'0');
str++;//pointer move a step
continue;
}else{
break;//non-didital character show up, abandon the rest of string
}//if-else
}//while pointer str did not reach the end '\0'
return opInt*sign;
}