61 lines
1.2 KiB
C++
61 lines
1.2 KiB
C++
#include "roman_numerals.h"
|
|
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
namespace roman {
|
|
|
|
using namespace std;
|
|
|
|
string convert(int number)
|
|
{
|
|
struct digit_t
|
|
{
|
|
int key;
|
|
string value;
|
|
};
|
|
|
|
static const vector<digit_t> digits = {
|
|
{1000, "M" },
|
|
{500, "D" },
|
|
{100, "C" },
|
|
{50, "L" },
|
|
{10, "X" },
|
|
{5, "V" },
|
|
{1, "I" }
|
|
};
|
|
|
|
string result;
|
|
|
|
auto append_digit = [&](int key, const string &value) -> void {
|
|
|
|
while (number >= key) {
|
|
|
|
result += value;
|
|
number -= key;
|
|
}
|
|
};
|
|
|
|
auto iter = digits.cbegin();
|
|
for (; iter != digits.cend(); ++iter) {
|
|
|
|
append_digit(iter->key, iter->value);
|
|
|
|
auto next_iter = next(iter);
|
|
|
|
while (next_iter != digits.cend()
|
|
&& 2*next_iter->key >= iter->key) {
|
|
++next_iter;
|
|
}
|
|
|
|
if (next_iter == digits.cend())
|
|
continue;
|
|
|
|
append_digit(iter->key - next_iter->key,
|
|
next_iter->value + iter->value);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
}
|