1.3 Roman to Integer
Description
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Method
Roman numeric system: https://en.wikipedia.org/wiki/Roman_numerals
for loop each character to get it's value and then do operations according to the rule of roman number.
when the left component > right component, add sum; or right component - left component;
Time and Space Complexity
o(n)
Code
public class Solution {
public int romanToInt(String s) {
if (s == "" || s.length() == 0){
return 0;
}
int val = 0;
int pre = 0;
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
int cur = helper(c);
if (cur <= pre){
val += cur;
} else {
val = val - pre + cur - pre;
}
pre = cur;
}
return val;
}
public int helper(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;
case 'M' : return 1000;
}
return 0;
}
}