From a9b0c969870bc2cec675141ae75f4e041f52e1d3 Mon Sep 17 00:00:00 2001 From: Dario Sindicic Date: Mon, 1 Oct 2018 18:53:31 +0200 Subject: [PATCH] roman numbers converter --- roman/roman.cpp | 61 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 roman/roman.cpp diff --git a/roman/roman.cpp b/roman/roman.cpp new file mode 100644 index 00000000..a40086c4 --- /dev/null +++ b/roman/roman.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include +using namespace std; + +string HELLO_MESSAGE = "Please enter roman number: "; +string RESULT = "Result is"; +string ERROR = "There were an error in the input."; + +string input; + +mapmapa; + +int roman_number(string S) { + int result = 0; + + int last_digit = -1; + for(int i = 0, len = S.length();i < len; ++i) { + if(mapa[S[i]] == 0) return -1; + + int digit_value = mapa[S[i]]; + if(last_digit == -1) { + result = digit_value; + last_digit = digit_value; + } else if(digit_value <= last_digit) { + result += digit_value; + last_digit = digit_value; + } else { //IX CM + result -= last_digit; + result += (digit_value - last_digit); + last_digit = digit_value; + } + } + + return result; +} + +void init_map() { + mapa['I'] = 1; + mapa['V'] = 5; + mapa['X'] = 10; + mapa['L'] = 50; + mapa['C'] = 100; + mapa['D'] = 500; + mapa['M'] = 1000; +} + +int main() { + cout << HELLO_MESSAGE; + cin >> input; + init_map(); + int result = roman_number(input); + if(result == -1) { + cout << ERROR; + } else { + cout << RESULT << " " << result << endl; + } + return 0; +}