题解 | #把字符串转换成整数(atoi)#

把字符串转换成整数(atoi)

https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f

#include <algorithm>
#include <cmath>
#include <climits>
class Solution {
 public:
  /**
   * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
   *
   *
   * @param s string字符串
   * @return int整型
   */
  int StrToInt(string s) {
    // write code here
    vector<vector<int>>  statesTable = {
      {0, 2, 2, 3, 1},
      {3, 1, 2, 3, 3},
      {3, 2, 2, 3, 3}
    };
    long top = INT_MAX;
    long bottom = INT_MIN;
    int n = s.size();
    int state = 0;
    long res = 0;
    int sign = 1;
    for (int i = 0; i < n; i++) {
      char c = s[i];
      if (c == ' ') {
        state = statesTable[state][0];
        if (state == 3) {
          break;
        }
      } else if (c == '0') {
        if (state == 2) {
          state = statesTable[state][1];
          res = res * 10 + (int) (c - '0');
          res = (sign > 0) ? min(res, top) : min(res, -bottom);
        } else {
          state = statesTable[state][1];
        }

      } else if (c >= '1' && c <= '9') {
        state = statesTable[state][2];
        res = res * 10 + (int) (c - '0');
        res = (sign > 0) ? min(res, top) : min(res, -bottom);
      } else if (c == '+' || c == '-') {
        if (state == 0) {
          state = statesTable[state][4];
          sign = (c == '+') ? 1 : -1;
        } else {
          break;
        }
      } else {
        state = statesTable[state][3];
        break;
      }
    }
    return (int)sign * res;
  }

};

一开始也以为自己写不出来,但是最终我写出来了!太棒了!

注意事项:

”0 -2“字符串转换之后为0, 因为0之后不能再接正负号。

这是我自己绘制的状态图:

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 17:13
想去,但是听说加班强度实在难崩,所以拒绝了,现在有点心梗对面hr感觉也是实习生,打电话的时候怪紧张的,但是感觉人很好嘞
水中水之下水道的鼠鼠:哥们这不先去体验一下,不行再跑呗,大不了混个实习经历(有更好的转正offer就当我没说)
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
05-29 20:12
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务