一. 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.
Difficulty:Medium
TIME:18MIN
解法
这道题的的意思是说把字符串转换为int类型的数字,转换的过程要满足一下几个要点:
- 遇到有效字符(+,-,0-9)前的空白符直接跳过
- 遇到非空白符非有效字符那么直接输出已经构造的数字(比如遇到字母)
- 遇到有效字符后除非遇到数字,不然直接输出已经构造的数字(比如-+2,输出0,+2-4输出2)
int myAtoi(string str) {
long result = 0;
int sign = 1;
bool show = false; //遇到有效字符的标记,一但遇到有效字符就将该标记置为true
for (int i = 0; i < str.size(); i++) {
if ((str[i] - '0') >= 0 && (str[i] - '0') <= 9) {
result = 10 * result + str[i] - '0';
show = true;
}
else if (show) //遇到有效字符后,除非是数字,不然就break
break;
else if (str[i] == '-') {
sign = -1;
show = true;
}
else if (str[i] == '+')
show = true;
else if (str[i] == '\n' || str[i] == '\r' || str[i] == ' ')
continue;
else //其余情况一律break
break;
if (result * sign > INT32_MAX)
return INT32_MAX;
else if (result * sign < INT32_MIN)
return INT32_MIN;
}
return (int)(result * sign);
}
代码的时间复杂度为 O(n) 。
总结
这道题并没有考虑8进制和16进制的情况,不过其实处理起来应该差不了多少。