Leetcode008-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.
尝试着自己去写,不看提示,发现还是有很多疏漏的地方,基本是靠着测试样例写通过了。总结起来基本可以分为:字符串处理问题、整数溢出问题、正负性问题。
AC版本
#include <limits>
#include <limits.h>
class Solution {
public:
int myAtoi(string str) {
int n = str.size();
if(!n)
return 0;
bool ispositive = true;
bool valid = true;
int res = 0;
// 删去开头空格
while(str[0] == ' '){
str.erase(0, 1);
n--;
}
// 判断正负
if(str[0] == '+' || str[0] == '-'){
if(n == 1)
return 0;
else if(str[0] == '-')
ispositive = false;
str.erase(0, 1);
n--;
}
for(int i=0; i<n; i++){
// 出现非数字字符
if(str[i]<'0' || str[i]>'9')
break;
int x = (int)(str[i]-'0');
// 判断是否溢出
if(numeric_limits<int>::max() / 10 >= res)
res = res * 10;
else{
valid = false;
break;
}
if(numeric_limits<int>::max() - x % 10 >= res)
res = res + x % 10;
else{
valid = false;
break;
}
}
if(ispositive && valid)
return res;
else if(!ispositive && valid)
return -res;
else if(ispositive && !valid)
return INT_MAX;
else if(!ispositive && !valid)
return INT_MIN;
}
};