Roman to Integer ( C++ )
Leetcode: Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
In order to solve this problem, I needed to first understand how to read roman numerals and translate them my hand.
https://www.mathsisfun.com/roman-numerals.html has a clear and concise explanation of a roman numerals. For this problem this chart is the only thing you need to really understand:
Rules of calculating Roman >> Integer
- (ADDING) The value of each symbol is (generally) added together from left to right:
- MMLVII (1,000+1,000+50+5+1+1) = 2,057
2. (SUBTRACTING) When there is a smaller number placed before a larger number
- XIX (10 + (10 − 1)) = 19
A simple solution was to have a for loop loop through each character in the string containing roman numerals and convert them to their integer value. Do calculations to the total as dictated by the above 2 rules of adding and subtracting.
int romanToInt(string s) {
int total = 0;
for(int i = 0; i < s.length(); i++){
//1.The letters are arranged from left to right
in descending order of value to form a number
if(integer_of(s[i]) <= interger_of[s[i]]) {
total += integer_of(s[i]);
}
//2.when you see a lower value in front of a
higher value (subtract)
else {
total += integer_of(s[i]);
}
} return total;
}
Best way to store the table to convert roman numerals to their corresponding integer values is by using a hash map:
map<char, int> m = {{'I', 1}, {'V', 5},{'X', 10},{'L', 50},{'C', 100},{'D', 500},{'M', 1000}};
Putting it all together:
int romanToInt(string s) {
map<char, int> m = {{'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++){
if(m[s[i+1]] <= m[s[i]]) total += m[s[i]];
else total -= m[s[i]];
}
return total;
}
Easy-Peasy Lemon Squeezy!
As always, I welcome feedback and discussion.