diff --git a/cpp/roman-numerals/roman_numerals.cpp b/cpp/roman-numerals/roman_numerals.cpp index e7db305..0b68c0a 100644 --- a/cpp/roman-numerals/roman_numerals.cpp +++ b/cpp/roman-numerals/roman_numerals.cpp @@ -1,7 +1,5 @@ #include "roman_numerals.h" -#include -#include namespace roman { @@ -11,48 +9,35 @@ string convert(int number) { struct digit_t { - int key; - string value; + int value; + string presentation; }; - static const vector digits = { + static const digit_t digits[] = { {1000, "M" }, + {900, "CM"}, {500, "D" }, + {400, "CD"}, {100, "C" }, + {90, "XC"}, {50, "L" }, + {40, "XL"}, {10, "X" }, + {9, "IX"}, {5, "V" }, + {4, "IV"}, {1, "I" } }; string result; - auto append_digit = [&](int key, const string &value) -> void { + for (auto &digit : digits) { - while (number >= key) { + while (number >= digit.value) { - 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; + result += digit.presentation; + number -= digit.value; } - - if (next_iter == digits.cend()) - continue; - - append_digit(iter->key - next_iter->key, - next_iter->value + iter->value); } return result;