描述:
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.
分析:
1) int型溢出
2) 异常输入,如“ -12a3”, " +222"
3) long long 型溢出
解决方案1:
通过我另一个博客中的atoi函数修改而来,时间复杂度O(n)
运行时间8ms
class Solution {
public:
int myAtoi(string str) {
long long intVal = 0; //最后返回的int值
int sign = 1; //1代表正数, -1代表负数
int k = 0;
std::string::iterator it = str.begin();
//跳过字符串前面的空格
while (*it == ' ')
it++;
//取得int值的符号
if (*it == '-')
sign = -1;
if (*it == '-' || *it == '+')
it++;
while (*it >= '0' && *it <= '9' && k <= 10) {
//ASCII码中'0'的值是0x30
intVal = intVal * 10 + ((int)*it - 0x30);
it++;
k++;
}
long long result = sign * intVal;
if (k >= 10) {
if(result < INT_MIN) return INT_MIN;
else if (result > INT_MAX) return INT_MAX;
} else {
return result;
}
}
};