-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8.string-to-integer-atoi.cpp
More file actions
122 lines (122 loc) · 2.37 KB
/
8.string-to-integer-atoi.cpp
File metadata and controls
122 lines (122 loc) · 2.37 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*
* @lc app=leetcode id=8 lang=cpp
*
* [8] String to Integer (atoi)
*/
// @lc code=start
class Solution
{
public:
long long POS_MAX = 2147483647;
long long NEG_MAX = POS_MAX + 1;
long long ERR_NUM = POS_MAX + 1000;
char get_char(string &s, int sp)
{
if (sp < s.length())
return s[sp];
return -1;
}
int get_sig(string &s, int sp)
{
char c = get_char(s, sp);
if (c == -1)
{
return -1;
}
if (c == '+')
{
return 1;
}
if (c == '-')
{
return 2;
}
return 0;
}
int skip_ws(string &s, int sp)
{
int cnt = 0;
while (1)
{
char c = get_char(s, sp);
if (c == -1)
{
return -1;
}
sp++;
if (c != ' ')
{
break;
}
cnt++;
}
return cnt;
}
char get_num_char(string &s, int sp)
{
char c = get_char(s, sp);
if (c == -1)
{
return -1;
}
if (c >= '0' && c <= '9')
{
return c;
}
return -1;
}
long long get_num(string &s, int sp, bool neg_flag)
{
long long num = 0;
while (1)
{
char c = get_num_char(s, sp);
sp++;
if (c == -1)
{
return num;
}
num = num * 10 + (c - '0');
if ((neg_flag && num >= NEG_MAX) || (!neg_flag && num >= POS_MAX))
{
if (neg_flag)
{
return NEG_MAX;
}
else
{
return POS_MAX;
}
}
}
}
int myAtoi(string s)
{
int sp = 0;
int o = skip_ws(s, sp);
if (o == -1)
{
return 0;
}
sp += o;
o = get_sig(s, sp);
if (o == -1)
{
return 0;
}
bool neg_flag = o == 2;
if (o != 0)
sp++;
long long num = get_num(s, sp, neg_flag);
if (num == ERR_NUM)
{
return 0;
}
if (neg_flag)
{
return -num;
}
return num;
}
};
// @lc code=end