Roman numerals are a number system that was originated from ancient Rome. Even though it is sort of obsolete, we often come across Roman numerals in various places. They are often used in movie titles, monarch names, chemistry periodic tables, sporting events among others. Sometimes it is difficult to read, especially the big numbers, for those who are not very familiar.
Here we’ll see how to write a C++ program to convert a roman number into a decimal one that we all are familiar with.
Let’s first get familiar with the symbols.
Symbol | I | V | X | L | C | D | M |
Value | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
Roman numerals are usually written largest to smallest from left to right. For example 3 is written as III (I + I + I), 12 is written as XII (X + I + I). However, 4 is not written as IIII, instead, it is written as IV to avoid clumsy 4 consecutive I’s. Here one is subtracted from five as it is placed before five, which makes the result 4. Similarly, 9 is written as IX.
There are six such instances where subtraction is used.
IV | 4 |
IX | 9 |
XL | 40 |
XC | 90 |
CD | 400 |
CM | 900 |
Logic to Convert Roman to Integer
- Maintain a running total, res, initialized with 0.
- For each input symbol:
- Get the decimal value of the current symbol and the next symbol.
- If the next symbol is not available or the current symbol value is higher than the next symbol value, add the numerical value of the symbol to the running total, res.
- Else, subtract the numerical value of the symbol to the running total, res.
The Program
#include <iostream>
#include <map>
#include <string>
using namespace std;
class Solution {
public:
int romanToInt(string str) {
int res = 0;
for (int i = 0; i < str.length(); i++) {
if (value_.find(str[i]) == value_.end()) return 0;
if ((i < str.length() -1) && (value_.find(str[i]) == value_.end())) return 0;
if ((i == str.length() - 1) || (value_.at(str[i]) >= value_.at(str[i + 1]))) {
res += value_.at(str[i]);
} else {
res -= value_.at(str[i]);
}
}
return res;
}
private:
const map<char, int> value_ = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
};
int main() {
Solution o;
string str = "MCMXCIV";
cout << "Integer of " << str << " is : " << o.romanToInt(str) << endl;
return 0;
}
Output of the program
$ g++ -std=c++11 -o test test.cpp
$ ./test
Integer of MCMXCIV is : 1994
please provide the code in c language it will be very helpful for me