题目描述:
实现标准库函数atoi,要解决空格字符问题,正负号问题,以及字母,溢出等问题,函数接收参数是string类型,返回值是int类型
英文描述
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.
这个题目在2015年2月10号修改过
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
下面是一些提示
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
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41int Solution008::atoi(string str)
{
const int max = 2147483647;
const int min = -2147483648;
bool positive = true;
int len = str.length();
double result = 0;
int idx;
for(idx = 0;idx<len;++idx)
{
if(str[idx] == ' ')
continue;
else
break;
}
if(str[idx] == '-' && idx < len)
{
positive = false;
idx ++;
}
else if(str[idx] == '+' && idx < len)
{
idx ++;
}
if(str[idx] < '0' || str[idx] > '9' || idx >= len)
return 0;
for(;idx <len;++idx)
{
if(str[idx] >= '0' && str[idx] <= '9')
{
result = result * 10 + (str[idx] - '0');
if(positive && result > max)
return max;
else if(!positive && (-1 * result) < min )
return min;
}
else
break;
}
return (positive ? result :(-1 * result));
}
解题思路
这道题目并不是很难,而且分类标准也是Easy,但是AC的比例比较低,开始的时候还真被这数字吓到了。
题目是不难,需要考虑多种情况。分为以下几个步骤:
- 首先去除字符串前缀空格;
- 然后判断有无正负号,若有正负号,设置正负号标志,指针后移一位,否则,不做处理;
- 判断第一个字符是否是数字,若不是,说明是无效数字,返回为0 ;否则正常处理;这个过程指针不移动;
- 循环处理后面的字符;若是数字字符,正常处理,并判断是否越界;若不是数字字符,退出循环,返回数字
参考
无