13. Roman to Integer
Asked at 34Bloomberg70Microsoft69Google65Meta63Amazon60Apple40IBM85tcs73AMD100Yahoo97Warnermedia78Virtusa77Tinkoff75Pwc73Cashfree66EPAM Systems60Zoho60Booking.com59Adobe55Oracle55Uber55Expedia54Capgemini52Wix52Deloitte50Snowflake48Accenture44Walmart Labs43TikTok35Infosys30DoorDash29Yandex28Goldman Sachs28Salesforce28
Problem
Convert a Roman numeral to an integer. The symbols are I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000, and a smaller symbol written before a larger one is subtracted (IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, CM = 900).
Example: "LVIII" → 58; "MCMXCIV" → 1994
Constraints: 1 ≤ value ≤ 3999.
Add each symbol's value, but subtract it when a larger symbol follows (IV, IX, XL, …).
Complexity: O(n).
class Solution:
def romanToInt(self, s: str) -> int:
val = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
total = 0
for i, ch in enumerate(s):
v = val[ch]
total += -v if i + 1 < len(s) and val[s[i + 1]] > v else v
return total
assert Solution().romanToInt("III") == 3
assert Solution().romanToInt("LVIII") == 58
assert Solution().romanToInt("MCMXCIV") == 1994
class Solution {
public int romanToInt(String s) {
int total = 0;
for (int i = 0; i < s.length(); i++) {
int v = val(s.charAt(i));
total += (i + 1 < s.length() && val(s.charAt(i + 1)) > v) ? -v : v;
}
return total;
}
private 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;
}
}
}
func romanToInt(s string) int {
val := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total := 0
for i := 0; i < len(s); i++ {
v := val[s[i]]
if i+1 < len(s) && val[s[i+1]] > v { // a smaller symbol before a larger one subtracts
total -= v
} else {
total += v
}
}
return total
}