看了下这道题在LeetCode上的难度属于中等,但是通过率不高。下面来看题目
[题目]
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.
这道题目的难点就在于他并没有给出规范的输入和输出要求,但是我们注意在题目的开头提及了atoi()这个函数,下面是atoi()函数的功能以及规范:[函数说明]
atoi( ) 函数会扫描参数 nptr字符串,跳过前面的空白字符(例如空格,tab缩进等,可以通过isspace( )函数来检测),直到遇上数字或正负符号才开
始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。如果 nptr不能转换成 int 或者 nptr为空字符串,那么将返回 0。
根据atoi的函数说明来看,我们可以得出以下几点:
- 我们可以将字符串的符号分为以下几类:
- 正负号:显而易见一个字符串中只能有一个正负号,当出现两个正负号的时候就可以断定该字符串不能转换成int,返回0;
- 空白字符:对于空白字符我们分为两种情况。一种是在开始转换之前,这种情况的空白字符可以直接忽略;第二种实在开始转换之后,这种情况我们结束转换并将结果返回;
- 0~9:对于0到9之间的字符我们进行正常的转换;
- 其他字符:所有的除上述字符以外的其他字符都是不合法的,我们直接结束转换并返回结果;
- 还需要注意的是在转换过程中我们需要注意数字的大小是否越界,int型变量的范围是2147483647或-2147483648,对于超过边界值得数值我们返回边界值
class Solution {
public:
int myAtoi(string str) {
int symbol = 1;
double num = 0;
bool plus_minus = false, start_transfer = false;
for (char &cha:str)
{
if (cha == '+' || cha == '-')
{
if (start_transfer || plus_minus)
{
num = 0;
break;
} else
{
symbol = (cha == '+') ? 1:-1;
plus_minus = true;
}
} else if (cha == ' ')
{
if (start_transfer || plus_minus)
{
break;
}
continue;
} else if (cha < '0' || cha > '9')
{
break;
} else
{
if (num > 2147483647)
{
num = 2147483647;
break;
} else if (num < -2147483648)
{
num = -2147483648;
break;
}
num = num * 10 + (cha - '0') * symbol;
}
}
return (int) num;
}
};