Problem: Given a roman numeral, convert it to an integer.
For example:
For example:
Input : "XVII" Output : 17 Input : "MMMDXLIX" Output : 3549Important points to remember:
- A number written in Arabic numerals can be broken into digits. For example, 1903 is composed of 1 (one thousand), 9 (nine hundreds), 0 (zero tens), and 3 (three units). To write the Roman numeral, each of the non-zero digits should be treated separately. In the above example, 1,000 = M, 900 = CM, and 3 = III. Therefore, 1903 = MCMIII.
- The symbols "I", "X", "C", and "M" can be repeated three times in succession, but no more. (They may appear more than three times if they appear non-sequentially, such as XXXIX.) "D", "L", and "V" can never be repeated.
- "I" can be subtracted from "V" and "X" only. "X" can be subtracted from "L" and "C" only. "C" can be subtracted from "D" and "M" only. "V", "L", and "D" can never be subtracted.
- Only one small-value symbol may be subtracted from any large-value symbol.
- Split the Roman Numeral string into Roman Symbols (character).
- Convert each symbol of Roman Numerals into the value it represents.
- Take symbol one by one from starting from index 0:
- If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.
- else subtract this value by adding the value of next symbol to the running total.
#include <bits/stdc++.h> using namespace std; /* function to get the value of different roman symbols */ int val(char c) { if(c=='M') return 1000; if(c=='D') return 500; if(c=='C') return 100; if(c=='L') return 50; if(c=='X') return 10; if(c=='V') return 5; if(c=='I') return 1; } /* function to returns decimal value of roman numeral */ int RomantoDecimal(string s) { /* initialize result */ int res = 0; /* traversing the input */ for(int i=0; i<s.length(); i++) { /* getting value of romain numeral s[i] */ int v1 = val(s[i]), v2; if(i+1 < s.length()) { /* getting value of romain numeral s[i + 1] */ v2 = val(s[i+1]); /* comparing the values */ if(v1 >= v2) { /* value of current symbol is greater or equal to the next symbol */ res = res + v1; } else { res = res + v2 - v1; i++; } } else { /* value of current symbol is less than the next symbol */ res += v1; i++; } } /* return ans */ return res; } /* main function */ int main() { string num = "MMMDXLIX"; cout<<RomantoDecimal(num)<<"\n"; return 0; }Output:
3549