From 0df74464b76ab2f062cacb1bbbc6a0ceb3033cc5 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Thu, 3 Nov 2022 16:09:44 +0800 Subject: [PATCH] s0013 --- include/s0013_roman_to_integer.hpp | 14 ++++++++++++++ src/s0013_roman_to_integer.cpp | 27 +++++++++++++++++++++++++++ tests/s0013_roman_to_integer.cpp | 24 ++++++++++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 include/s0013_roman_to_integer.hpp create mode 100644 src/s0013_roman_to_integer.cpp create mode 100644 tests/s0013_roman_to_integer.cpp diff --git a/include/s0013_roman_to_integer.hpp b/include/s0013_roman_to_integer.hpp new file mode 100644 index 0000000..487e5de --- /dev/null +++ b/include/s0013_roman_to_integer.hpp @@ -0,0 +1,14 @@ +#ifndef S0013_ROMAN_TO_INTEGER +#define S0013_ROMAN_TO_INTEGER + +#include +#include + +using namespace std; + +class Solution { + public: + int romanToInt(string s); +}; + +#endif diff --git a/src/s0013_roman_to_integer.cpp b/src/s0013_roman_to_integer.cpp new file mode 100644 index 0000000..32a80bb --- /dev/null +++ b/src/s0013_roman_to_integer.cpp @@ -0,0 +1,27 @@ +#include "s0013_roman_to_integer.hpp" + +int Solution::romanToInt(string s) { + unordered_map map; + map["I"] = 1; + map["V"] = 5; + map["X"] = 10; + map["L"] = 50; + map["C"] = 100; + map["D"] = 500; + map["M"] = 1000; + + int val{0}; + int len = s.length(); + for (int i{0}; i < len; i++) { + if (i == len - 1) { + val += map.at(s.substr(i, 1)); + } else { + if (map.at(s.substr(i, 1)) < map.at(s.substr(i + 1, 1))) { + val -= map.at(s.substr(i, 1)); + } else { + val += map.at(s.substr(i, 1)); + } + } + } + return val; +} diff --git a/tests/s0013_roman_to_integer.cpp b/tests/s0013_roman_to_integer.cpp new file mode 100644 index 0000000..941fce9 --- /dev/null +++ b/tests/s0013_roman_to_integer.cpp @@ -0,0 +1,24 @@ +#include "s0013_roman_to_integer.hpp" + +#include + +TEST(Problem13, Case1) { + string i("III"); + int o{3}; + Solution solution; + EXPECT_EQ(solution.romanToInt(i), o); +} + +TEST(Problem13, Case2) { + string i("LVIII"); + int o{58}; + Solution solution; + EXPECT_EQ(solution.romanToInt(i), o); +} + +TEST(Problem13, Case3) { + string i("MCMXCIV"); + int o{1994}; + Solution solution; + EXPECT_EQ(solution.romanToInt(i), o); +}