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.
思路:
思路很简单,主要是考虑溢出的方法。
代码
if(str == NULL)
{
return 0;
}
int len=strlen(str);
int res=0;
int sign=1;
int i=0;
while(i<len)
{
if(*str==' ')
{
str++;
}
else
break;
}
if(*str=='-')
{
sign=-1;
str++;
}
else if(*str=='+')
{
str++;
}
int digit=0;
int max=2147483647;
int min=-2147483648;
while(*str>='0' && *str<='9')
{
digit=*str-'0';
if(max/10>=res)
{
res*=10;
}
else
{
return sign==-1?min:max;
}
if(max-digit>=res)
{
res+=digit;
}
else
{
return sign==-1?min:max;
}
str++;
}
return res*sign;
本文介绍了一个将字符串转换为整数(atoi)的实现方案。重点在于如何处理可能的输入情况,包括忽略前导空格、判断正负号、读取数字字符并将其解析为数值,以及如何处理溢出问题。
295

被折叠的 条评论
为什么被折叠?



