This commit is contained in:
parent
090003819d
commit
e865d369e6
13
include/s0012_integer_to_roman.hpp
Normal file
13
include/s0012_integer_to_roman.hpp
Normal file
@ -0,0 +1,13 @@
|
||||
#ifndef S0012_INTEGER_TO_ROMAN
|
||||
#define S0012_INTEGER_TO_ROMAN
|
||||
|
||||
#include <string>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
string intToRoman(int num);
|
||||
};
|
||||
|
||||
#endif
|
19
src/s0012_integer_to_roman.cpp
Normal file
19
src/s0012_integer_to_roman.cpp
Normal file
@ -0,0 +1,19 @@
|
||||
#include "s0012_integer_to_roman.hpp"
|
||||
|
||||
// 贪心哈希表
|
||||
// 先硬编码一个哈希表
|
||||
// 然后当数值大于一个值的时候,就直接把对应的字符串加上去
|
||||
|
||||
string Solution::intToRoman(int num) {
|
||||
int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
|
||||
string reps[] = {"M", "CM", "D", "CD", "C", "XC", "L",
|
||||
"XL", "X", "IX", "V", "IV", "I"};
|
||||
string res;
|
||||
for (int i = 0; i < 13; i++) {
|
||||
while (num >= values[i]) {
|
||||
num -= values[i];
|
||||
res += reps[i];
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
24
tests/s0012_integer_to_roman.cpp
Normal file
24
tests/s0012_integer_to_roman.cpp
Normal file
@ -0,0 +1,24 @@
|
||||
#include "s0012_integer_to_roman.hpp"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
TEST(Problem12, Case1) {
|
||||
int i{3};
|
||||
string o("III");
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.intToRoman(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem12, Case2) {
|
||||
int i{58};
|
||||
string o("LVIII");
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.intToRoman(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem12, Case3) {
|
||||
int i{1994};
|
||||
string o("MCMXCIV");
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.intToRoman(i), o);
|
||||
}
|
Loading…
Reference in New Issue
Block a user