Practice › Strings
Roman to Integer
Easy · Strings · Asked at Amazon, Microsoft, Google, TCS, Infosys
Convert a Roman numeral to an integer. Symbols: I=1, V=5, X=10, L=50, C=100, D=500, M=1000. A smaller symbol before a larger one is subtracted (IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, CM = 900).
Input
One valid Roman numeral.
Output
Its integer value.
Constraints
- The value is between 1 and 3999
Example 1
Input
LVIII
Output
58
Example 2
Input
MCMXCIV
Output
1994
Hints
- Normally you just add up the symbol values.
- If a symbol is smaller than the one after it (like I before V), subtract it instead.
Approach
Map each symbol to its value and scan left to right. If the current value is smaller than the next symbol's value, it's a subtractive pair (IV, XC, CM…), so subtract it. Otherwise add it. MCMXCIV → 1000 − 100 + 1000 − 10 + 100 − 1 + 5 = 1994.
Complexity: O(n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int val(char c) {
switch (c) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
default: return 1000;
}
}
int main() {
string s;
cin >> s;
int total = 0;
for (size_t i = 0; i < s.size(); i++) {
if (i + 1 < s.size() && val(s[i]) < val(s[i + 1])) total -= val(s[i]);
else total += val(s[i]);
}
cout << total << "\n";
return 0;
}Python solution
VAL = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
s = input().strip()
total = 0
for i, ch in enumerate(s):
if i + 1 < len(s) and VAL[ch] < VAL[s[i + 1]]:
total -= VAL[ch]
else:
total += VAL[ch]
print(total)Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
Map<Character, Integer> val = Map.of('I', 1, 'V', 5, 'X', 10, 'L', 50, 'C', 100, 'D', 500, 'M', 1000);
int total = 0;
for (int i = 0; i < s.length(); i++) {
int v = val.get(s.charAt(i));
if (i + 1 < s.length() && v < val.get(s.charAt(i + 1))) total -= v;
else total += v;
}
System.out.println(total);
}
}