roman_numerals: working solution
This commit is contained in:
parent
bbfb9da1a1
commit
01e3033b83
2 changed files with 71 additions and 0 deletions
61
cpp/roman-numerals/roman_numerals.cpp
Normal file
61
cpp/roman-numerals/roman_numerals.cpp
Normal file
|
|
@ -0,0 +1,61 @@
|
||||||
|
#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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
10
cpp/roman-numerals/roman_numerals.h
Normal file
10
cpp/roman-numerals/roman_numerals.h
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#define EXERCISM_RUN_ALL_TESTS
|
||||||
|
|
||||||
|
namespace roman {
|
||||||
|
|
||||||
|
std::string convert(int);
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue