一、
String to Integer (atoi)
这一题主要难点在于考虑条件。
符合规定条件:1、+123,-123,123;
2、1323s
3、_ _ _ _134
4、0000123,+000123,-000123
不符合条件的情况:1、-+123,s123,-s123
2、数据溢出
代码:
class Solution {
public:
int myAtoi(string str) {
if (str == "") return 0;
int result = 0;
int flag = 0;
int strEnd = str.length() - 1;
int sign = 1;
int flagBegin = 0;
int INT_MAX_MIN_PRE = INT_MAX / 10;
int INT_MAX_LAST = INT_MAX % 10;
int INT_MIN_LAST = INT_MAX_LAST + 1;
while (flag <= strEnd){
if (str[flag] != ' ') break;
flag++;
}
if (str[flag] == '-'){
sign = -1;
flag++;
}
else if (str[flag] == '+') flag++;
while (flag <= strEnd){
if (str[flag] != '0') break;
flag++;
}
while (flag <= strEnd){
if (str[flag] > '9' || str[flag] < '0') break;
if (sign == 1 && (result > INT_MAX_MIN_PRE || (result == INT_MAX_MIN_PRE && str[flag] - '0' > INT_MAX_LAST))){
return INT_MAX;
}
if (sign == -1 && (result > INT_MAX_MIN_PRE || (result == INT_MAX_MIN_PRE && str[flag] - '0' > INT_MIN_LAST))){
return INT_MIN;
}
result = result * 10 + str[flag] - '0';
flag++;
}
return result * sign;
}
};