LeetCode——8. 字符串转换整数 (atoi)(C++)

 该题链接:https://leetcode-cn.com/problems/string-to-integer-atoi/comments/

#include 
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<

 

你可能感兴趣的:(LeetCode,字符串转换整数,C++)