From 67d21139ebe1c31102cd2e5878e1dc07433708d9 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Wed, 2 Nov 2022 22:02:42 +0800 Subject: [PATCH] s0008 --- include/s0008_string_to_integer.hpp | 15 +++++++++++ src/s0008_string_to_integer.cpp | 39 +++++++++++++++++++++++++++++ tests/s0008_string_to_integer.cpp | 24 ++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 include/s0008_string_to_integer.hpp create mode 100644 src/s0008_string_to_integer.cpp create mode 100644 tests/s0008_string_to_integer.cpp diff --git a/include/s0008_string_to_integer.hpp b/include/s0008_string_to_integer.hpp new file mode 100644 index 0000000..5ecd22b --- /dev/null +++ b/include/s0008_string_to_integer.hpp @@ -0,0 +1,15 @@ +#ifndef S0008_STRING_TO_INTEGER +#define S0008_STRING_TO_INTEGER + +#include +#include +#include + +using namespace std; + +class Solution { +public: + int myAtoi(string s); +}; + +#endif diff --git a/src/s0008_string_to_integer.cpp b/src/s0008_string_to_integer.cpp new file mode 100644 index 0000000..ef3674f --- /dev/null +++ b/src/s0008_string_to_integer.cpp @@ -0,0 +1,39 @@ +#include "s0008_string_to_integer.hpp" + +// 当流程很复杂的时候,画流程图: https://paste.sainnhe.dev/NQxx.png + +class Automaton { + string state = "start"; + unordered_map> 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; +} diff --git a/tests/s0008_string_to_integer.cpp b/tests/s0008_string_to_integer.cpp new file mode 100644 index 0000000..6ab0bb3 --- /dev/null +++ b/tests/s0008_string_to_integer.cpp @@ -0,0 +1,24 @@ +#include "s0008_string_to_integer.hpp" + +#include + +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); +}