2026/05/13

[LeetCode] 8 String to Integer (atoi)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
private:
  string trimLeadingSpace(string s) {
    int i = 0;
    while (i < s.size() && s[i] == ' ')
      i++;
    return s.substr(i);
  }

  string trimSignedness(string s, int &sign) {
    int i = 0;
    sign = 1;
    if (s[i] == '-') {
      sign = -1;
      i++;
    } else if (s[i] == '+')
      i++;
    return s.substr(i);
  }

  int convert2Int(string s, int sign) {
    int i = 0;
    long long int result = 0;
    while (i < s.size() && std::isdigit(s[i])) {
      result = result * 10 + (s[i] - '0');

      if (sign * result > INT_MAX)
        return INT_MAX;
      if (sign * result < INT_MIN)
        return INT_MIN;

      i++;
    }
    return static_cast<int>(sign * result);
  }

public:
  int myAtoi(string s) {
    s = trimLeadingSpace(s);
    int sign = 1;
    s = trimSignedness(s, sign);
    int ret = convert2Int(s, sign);
    return ret;
  }
};