LeetCode8. 字符串转换整数 (atoi)
字符串转整数。链接:https://leetcode-cn.com/problems/string-to-integer-atoi/
题解:模拟题
class Solution {
public:
int myAtoi(string str) {
int flag = 0;
long long temp = 0;
for (int i = 0; i < str.length(); i++) {
if (flag) {
if (str[i] >= '0'&&str[i] <= '9') {
temp = temp * 10 + (str[i] - '0');
if (flag == -1) {
if (-temp < INT_MIN)return INT_MIN;
}
else if(flag==1){
if (temp > INT_MAX)return INT_MAX;
}
}
else {
if (flag == -1) return -temp;
return temp;
}
}
else {
if ( str[i]==' ')continue;
else if(str[i]=='-'){
flag = -1;
}
else if (str[i] == '+') {
flag = 1;
}
else if (str[i]<'0' || str[i]>'9') {
return temp;
}
else {
flag = 1;
temp = str[i] - '0';
}
}
//cout << "--------------" << temp << "-----------" << endl;
}
if (flag == -1) return -temp;
return temp;
}
};