From 01e3033b83fbaf86298156a01d2cfabda8a43bb3 Mon Sep 17 00:00:00 2001 From: Dmitry Kokorin Date: Thu, 24 Mar 2016 18:13:59 +0300 Subject: [PATCH] roman_numerals: working solution --- cpp/roman-numerals/roman_numerals.cpp | 61 +++++++++++++++++++++++++++ cpp/roman-numerals/roman_numerals.h | 10 +++++ 2 files changed, 71 insertions(+) create mode 100644 cpp/roman-numerals/roman_numerals.cpp create mode 100644 cpp/roman-numerals/roman_numerals.h diff --git a/cpp/roman-numerals/roman_numerals.cpp b/cpp/roman-numerals/roman_numerals.cpp new file mode 100644 index 0000000..e7db305 --- /dev/null +++ b/cpp/roman-numerals/roman_numerals.cpp @@ -0,0 +1,61 @@ +#include "roman_numerals.h" + +#include +#include + +namespace roman { + +using namespace std; + +string convert(int number) +{ + struct digit_t + { + int key; + string value; + }; + + static const vector 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; +} + +} diff --git a/cpp/roman-numerals/roman_numerals.h b/cpp/roman-numerals/roman_numerals.h new file mode 100644 index 0000000..09d755b --- /dev/null +++ b/cpp/roman-numerals/roman_numerals.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +#define EXERCISM_RUN_ALL_TESTS + +namespace roman { + +std::string convert(int); +}