This commit is contained in:
parent
e865d369e6
commit
0df74464b7
14
include/s0013_roman_to_integer.hpp
Normal file
14
include/s0013_roman_to_integer.hpp
Normal file
@ -0,0 +1,14 @@
|
||||
#ifndef S0013_ROMAN_TO_INTEGER
|
||||
#define S0013_ROMAN_TO_INTEGER
|
||||
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
int romanToInt(string s);
|
||||
};
|
||||
|
||||
#endif
|
27
src/s0013_roman_to_integer.cpp
Normal file
27
src/s0013_roman_to_integer.cpp
Normal file
@ -0,0 +1,27 @@
|
||||
#include "s0013_roman_to_integer.hpp"
|
||||
|
||||
int Solution::romanToInt(string s) {
|
||||
unordered_map<string, int> 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;
|
||||
}
|
24
tests/s0013_roman_to_integer.cpp
Normal file
24
tests/s0013_roman_to_integer.cpp
Normal file
@ -0,0 +1,24 @@
|
||||
#include "s0013_roman_to_integer.hpp"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
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);
|
||||
}
|
Loading…
Reference in New Issue
Block a user