roman_numerals: iteration 1
This commit is contained in:
parent
01e3033b83
commit
fee57a8bab
1 changed files with 13 additions and 28 deletions
|
|
@ -1,7 +1,5 @@
|
||||||
#include "roman_numerals.h"
|
#include "roman_numerals.h"
|
||||||
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace roman {
|
namespace roman {
|
||||||
|
|
||||||
|
|
@ -11,48 +9,35 @@ string convert(int number)
|
||||||
{
|
{
|
||||||
struct digit_t
|
struct digit_t
|
||||||
{
|
{
|
||||||
int key;
|
int value;
|
||||||
string value;
|
string presentation;
|
||||||
};
|
};
|
||||||
|
|
||||||
static const vector<digit_t> digits = {
|
static const digit_t digits[] = {
|
||||||
{1000, "M" },
|
{1000, "M" },
|
||||||
|
{900, "CM"},
|
||||||
{500, "D" },
|
{500, "D" },
|
||||||
|
{400, "CD"},
|
||||||
{100, "C" },
|
{100, "C" },
|
||||||
|
{90, "XC"},
|
||||||
{50, "L" },
|
{50, "L" },
|
||||||
|
{40, "XL"},
|
||||||
{10, "X" },
|
{10, "X" },
|
||||||
|
{9, "IX"},
|
||||||
{5, "V" },
|
{5, "V" },
|
||||||
|
{4, "IV"},
|
||||||
{1, "I" }
|
{1, "I" }
|
||||||
};
|
};
|
||||||
|
|
||||||
string result;
|
string result;
|
||||||
|
|
||||||
auto append_digit = [&](int key, const string &value) -> void {
|
for (auto &digit : digits) {
|
||||||
|
|
||||||
while (number >= key) {
|
while (number >= digit.value) {
|
||||||
|
|
||||||
result += value;
|
result += digit.presentation;
|
||||||
number -= key;
|
number -= digit.value;
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
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;
|
return result;
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue