LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
class Solution {
 public:
  int myAtoi(string s) {
    if (empty(s)) {
      return 0;
    }
    long res = 0;
    int cur = 0;
    bool postive = true;
    // 去掉开头所有空字符
    while (cur < size(s) && s[cur] == ' ') {
      ++cur;
    }
    if (cur >= size(s)) {
      return 0;
    }
    // 检查有无正负号
    if (s[cur] == '+') {
      ++cur;
    } else if (s[cur] == '-') {
      postive = false;
      ++cur;
    }
    // 检查每个字符都是数字,并计算结果
    while (cur < size(s) && isdigit(s[cur])) {
      if (res > INT_MAX) {  // 溢出时退出
        break;
      }
      res = res * 10 + (s[cur] - '0');
      ++cur;
    }
    if (!postive) {
      res = -res;
    }
    if (res >= INT_MAX) {
      return INT_MAX;
    }
    if (res <= INT_MIN) {
      return INT_MIN;
    }
    return res;
  }
};