Roman to Integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
Ican be placed beforeV(5) andX(10) to make 4 and 9.Xcan be placed beforeL(50) andC(100) to make 40 and 90.Ccan be placed beforeD(500) andM(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Example 1:
Input: s = "III"
Output: 3
Explanation: III = 3.Example 2:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.Example 3:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= s.length <= 15scontains only the characters('I', 'V', 'X', 'L', 'C', 'D', 'M').It is guaranteed that
sis a valid roman numeral in the range[1, 3999].
Solutions
The problem is to convert a Roman numeral to an integer. The solution involves a process of iterating over the Roman numeral from left to right. For each character, it adds its corresponding integer value to the result. If a character represents a value that is less than the next character’s value, it subtracts this value instead of adding it. The final result is the integer representation of the original Roman numeral.
Approach - Brute Force Technique
Checks each character in the string one by one.
Steps
Dictionary Initialization: A dictionary
romanLattersis initialized with Roman numerals as keys and their corresponding integer values as values.Input Validation: The
IsValidInputfunction checks if the input stringsis within the valid length (1 to 15 characters) and if all characters insare valid Roman numerals. If the input string is invalid, the function returnsfalse, and theRomanToIntfunction will return zero.Roman Numeral Conversion: The
RomanToIntfunction converts the input Roman numeral to an integer. It initializes an integeroutputto store the result and a variablepreto keep track of the value of the previous Roman numeral.Iteration Over String: The function iterates over each character in the input string
s. For each character, it gets the corresponding integer valuecurrentfrom theromanLattersdictionary.Addition and Subtraction: If
preis zero orpreis greater than or equal tocurrent, the function addscurrenttooutput. Otherwise, it subtractsprefromoutputand addscurrent - pretooutput.Update Previous Value: After processing each character, the function updates
pretocurrent.Completion: The function continues this process until all characters in the string have been processed. At this point,
outputis the integer equivalent of the input Roman numeral.Return Result: Finally, the function returns the integer
output.
public class Solution {
public Dictionary<char,int> romanLatters=new Dictionary<char,int>()
{
{'I',1},
{'V',5},
{'X',10},
{'L',50},
{'C',100},
{'D',500},
{'M',1000}
};
public int RomanToInt(string s) {
int output=0;
if(IsValidInput(s)){
int pre=0;
foreach(char ch in s.ToArray()){
int current=romanLatters[ch];
if(pre==0 || pre>=current){
output+=current;
}
else {
output = output - pre;
output = output + (current-pre);
}
pre=current;
}
}
return output;
}
private bool IsValidInput(string input){
return 1<=input.Length && input.Length<=15 &&IsValidRomanInput(input);
}
private bool IsValidRomanInput(string input){
foreach(char item in input.ToArray()){
if(!romanLatters.ContainsKey(item)){
return false;
}
}
return true;
}
}Complexity
Time Complexity: O(1)
Auxiliary Space: O(1)
Time Complexity: The time complexity is O(1). This is because the max length of string is 15 characters.
Space Complexity: The space complexity is O(1). The space used by the program does not grow with the size of the input string. The dictionary of Roman numerals uses a constant amount of space, and the integer variables output and pre also use a constant amount of space.
Please note that this analysis assumes that dictionary lookups can be done in constant time.
Approach - Iterative Technique
The solution involves a process of iterating over the Roman numeral from left to right. For each character, it checks if it represents a value that is less than the next character’s value. If it is, it subtracts this value from the result. Otherwise, it adds this value to the result. The final result is the integer representation of the original Roman numeral.
Steps
Dictionary Initialization: A dictionary
romanLattersis initialized with Roman numerals as keys and their corresponding integer values as values.Input Validation: The
IsValidInputfunction checks if the input stringsis within the valid length (1 to 15 characters) and if all characters insare valid Roman numerals. If the input string is invalid, the function returnsfalse, and theRomanToIntfunction will return zero.Roman Numeral Conversion: The
RomanToIntfunction converts the input Roman numeral to an integer. It initializes an integeroutputto store the result.Iteration Over String: The function iterates over each character in the input string
susing aforloop. For each character, it gets the corresponding integer valuecurrentfrom theromanLattersdictionary.Addition and Subtraction: Inside the
forloop, it checks if the current character’s value is less than the next character’s value. If it is, it subtractscurrentfromoutput. Otherwise, it addscurrenttooutput.Completion: The function continues this process until all characters in the string have been processed. At this point,
outputis the integer equivalent of the input Roman numeral.Return Result: Finally, the function returns the integer
output.
public class Solution {
public Dictionary<char,int> romanLatters=new Dictionary<char,int>()
{
{'I',1},
{'V',5},
{'X',10},
{'L',50},
{'C',100},
{'D',500},
{'M',1000}
};
public int RomanToInt(string s) {
int output=0;
if(IsValidInput(s)){
int pre=0;
for(int i=0; i<s.Length; i++){
int current=romanLatters[s[i]];
if(i+1<s.Length && current<romanLatters[s[i+1]]){
output-=current;
}
else {
output+=current;
}
pre=current;
}
}
return output;
}
private bool IsValidInput(string input){
return 1<=input.Length && input.Length<=15 &&IsValidRomanInput(input);
}
private bool IsValidRomanInput(string input){
foreach(char item in input.ToArray()){
if(!romanLatters.ContainsKey(item)){
return false;
}
}
return true;
}
}
Complexity
Time Complexity: O(1)
Auxiliary Space: O(1)
Time Complexity: The time complexity is O(1). This is because the max length of string is 15 characters.
Space Complexity: The space complexity is O(1). The space used by the program does not grow with the size of the input string. The dictionary of Roman numerals uses a constant amount of space, and the integer variables output and pre also use a constant amount of space.
Please note that this analysis assumes that dictionary lookups can be done in constant time.
Last updated