s0008
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
Sainnhe Park 2022-11-02 22:02:42 +08:00
parent 59d1cb7245
commit 67d21139eb
3 changed files with 78 additions and 0 deletions

View 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

View 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;
}

View 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);
}