From efae9b1a22c177320526c94bc540bc2ed8ecc515 Mon Sep 17 00:00:00 2001 From: Kriti1262 <100215152+Kriti1262@users.noreply.github.com> Date: Mon, 10 Oct 2022 23:46:55 +0530 Subject: [PATCH] Create RomanToInteger.cpp --- RomanToInteger.cpp | 74 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 RomanToInteger.cpp diff --git a/RomanToInteger.cpp b/RomanToInteger.cpp new file mode 100644 index 0000000..ff9b2a9 --- /dev/null +++ b/RomanToInteger.cpp @@ -0,0 +1,74 @@ +// Program to convert Roman +// Numerals to Numbers +#include +using namespace std; + +// This function returns value +// of a Roman symbol +int value(char r) +{ + if (r == 'I') + return 1; + if (r == 'V') + return 5; + if (r == 'X') + return 10; + if (r == 'L') + return 50; + if (r == 'C') + return 100; + if (r == 'D') + return 500; + if (r == 'M') + return 1000; + + return -1; +} + +// Returns decimal value of +// roman numaral +int romanToDecimal(string& str) +{ + // Initialize result + int res = 0; + + // Traverse given input + for (int i = 0; i < str.length(); i++) { + // Getting value of symbol s[i] + int s1 = value(str[i]); + + if (i + 1 < str.length()) { + // Getting value of symbol s[i+1] + int s2 = value(str[i + 1]); + + // Comparing both values + if (s1 >= s2) { + // Value of current symbol + // is greater or equal to + // the next symbol + res = res + s1; + } + else { + // Value of current symbol is + // less than the next symbol + res = res + s2 - s1; + i++; + } + } + else { + res = res + s1; + } + } + return res; +} + +// Driver Code +int main() +{ + // Considering inputs given are valid + string str = "MCMIV"; + cout << "Integer form of Roman Numeral is " + << romanToDecimal(str) << endl; + + return 0; +}