该题链接:https://leetcode-cn.com/problems/string-to-integer-atoi/comments/
#include <bits/stdc++.h>
using namespace std;
/*
每一步都要记得把符号位乘上
该算法提交结果超过了Leetcode 100%的用户,性能还行,代码也不算臃肿
*/
class Solution
{
public:
int myAtoi(string str)
{
int max = INT_MAX / 10;
int min = INT_MIN / 10;
int max_f = INT_MAX % 10;
int min_f = INT_MIN % 10;
int len = str.length();
bool flag = false; // 记录有没有开始计数
int sum = 0;
int symbol = 1;
for(int i = 0; i < len; i++)
{
char ch = str[i];
if(!flag)
{
if(ch == ' ') continue;
else if(ch == '+') flag = true;
else if(ch == '-')
{
flag = true;
symbol = -1;
}
else if(ch <= '9' && ch >= '0') flag = true;
else break;
}
else if(ch > '9' || ch < '0') break;
if(ch <= '9' && ch >= '0')
{
int pos = symbol * (ch - '0');
if(sum > max || (sum == max && pos >= max_f)) return INT_MAX;
if(sum < min || (sum == min && pos <= min_f)) return INT_MIN;
sum = sum * 10 + pos;
}
}
return sum;
}
};
int main()
{
Solution sol;
cout<<sol.myAtoi("42")<<endl; // 42
cout<<sol.myAtoi(" -42")<<endl; // -42
cout<<sol.myAtoi(" -042")<<endl; // -42
cout<<sol.myAtoi("4193 with words")<<endl; // 4193
cout<<sol.myAtoi("what -430")<<endl; // 0
cout<<sol.myAtoi("-91283472332")<<endl; // -2147483648
cout<<sol.myAtoi("91283472332")<<endl; // 2147483647
cout<<sol.myAtoi("-2147483648")<<endl; // -2147483648
return 0;
}