This commit is contained in:
parent
59d1cb7245
commit
67d21139eb
15
include/s0008_string_to_integer.hpp
Normal file
15
include/s0008_string_to_integer.hpp
Normal file
@ -0,0 +1,15 @@
|
||||
#ifndef S0008_STRING_TO_INTEGER
|
||||
#define S0008_STRING_TO_INTEGER
|
||||
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
int myAtoi(string s);
|
||||
};
|
||||
|
||||
#endif
|
39
src/s0008_string_to_integer.cpp
Normal file
39
src/s0008_string_to_integer.cpp
Normal file
@ -0,0 +1,39 @@
|
||||
#include "s0008_string_to_integer.hpp"
|
||||
|
||||
// 当流程很复杂的时候,画流程图: https://paste.sainnhe.dev/NQxx.png
|
||||
|
||||
class Automaton {
|
||||
string state = "start";
|
||||
unordered_map<string, vector<string>> table = {
|
||||
{"start", {"start", "signed", "in_number", "end"}},
|
||||
{"signed", {"end", "end", "in_number", "end"}},
|
||||
{"in_number", {"end", "end", "in_number", "end"}},
|
||||
{"end", {"end", "end", "end", "end"}}};
|
||||
|
||||
int get_col(char c) {
|
||||
if (isspace(c)) return 0;
|
||||
if (c == '+' or c == '-') return 1;
|
||||
if (isdigit(c)) return 2;
|
||||
return 3;
|
||||
}
|
||||
|
||||
public:
|
||||
int sign = 1;
|
||||
long long ans = 0;
|
||||
|
||||
void get(char c) {
|
||||
state = table[state][get_col(c)];
|
||||
if (state == "in_number") {
|
||||
ans = ans * 10 + c - '0';
|
||||
ans = sign == 1 ? min(ans, (long long)INT_MAX)
|
||||
: min(ans, -(long long)INT_MIN);
|
||||
} else if (state == "signed")
|
||||
sign = c == '+' ? 1 : -1;
|
||||
}
|
||||
};
|
||||
|
||||
int Solution::myAtoi(string str) {
|
||||
Automaton automaton;
|
||||
for (char c : str) automaton.get(c);
|
||||
return automaton.sign * automaton.ans;
|
||||
}
|
24
tests/s0008_string_to_integer.cpp
Normal file
24
tests/s0008_string_to_integer.cpp
Normal file
@ -0,0 +1,24 @@
|
||||
#include "s0008_string_to_integer.hpp"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
TEST(Problem8, Case1) {
|
||||
string i = std::string("42");
|
||||
int o = 42;
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.myAtoi(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem8, Case2) {
|
||||
string i = std::string(" -42");
|
||||
int o = -42;
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.myAtoi(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem8, Case3) {
|
||||
string i = std::string("4193 with words");
|
||||
int o = 4193;
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.myAtoi(i), o);
|
||||
}
|
Loading…
Reference in New Issue
Block a user