-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0008_StringToInteger.cpp
More file actions
74 lines (69 loc) · 1.97 KB
/
Copy path0008_StringToInteger.cpp
File metadata and controls
74 lines (69 loc) · 1.97 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
#include <fmt/ranges.h>
#include <string>
#include <sys/stat.h>
class Solution
{
static constexpr auto makeRomanParser()
{
enum State { Start, Numbers, Invalid };
return [value = 0, state = Start, sign = 1](const char input) mutable -> int32_t {
switch (state) {
case Start:
if (input == ' ') {
return 0;
}
if (input == '-') {
sign = -1;
state = Numbers;
return value;
}
if (input == '+') {
sign = 1;
state = Numbers;
return value;
}
[[fallthrough]];
case Numbers:
if (input >= '0' && input <= '9') {
state = Numbers;
value = static_cast<int32_t>(
std::clamp(static_cast<int64_t>(value) * 10 + sign * (input - '0'),
static_cast<int64_t>(INT_MIN),
static_cast<int64_t>(INT_MAX)));
return value;
}
[[fallthrough]];
case Invalid:
state = Invalid;
return value;
default:
return 0;
}
};
}
public:
int myAtoi(std::string s)
{
auto parser = makeRomanParser();
int result = 0;
for (const auto &c : s) {
result = parser(c);
}
return result;
}
};
int main()
{
Solution sol;
// test cases
std::string s1 = "42";
std::string s2 = " -042";
std::string s3 = "-1337c0d3";
std::string s4 = "0-1";
std::string s5 = "words and 987";
std::string s6 = "-91283472332";
std::string s7 = "+1";
for (auto s : {s1, s2, s3, s4, s5, s6, s7}) {
fmt::print("Before: [{}] After: [{}]\n", s, sol.myAtoi(s));
}
}