2017.10.27
public class Solution {
/*
* @param s: Roman representation
* @return: an integer
*/
public int romanToInt(String s){
HashMap<Character,Integer> map = new HashMap<>();
map.put('I', 1);
map.put('X', 10);
map.put('C', 100);
map.put('M', 1000);
map.put('V', 5);
map.put('L', 50);
map.put('D', 500);
if(s.length() == 0){
return 0;
}
if(s.length() == 1){
return map.get(s.charAt(0));
}
int res = 0;
for(int i = s.length()-1; i >= 0; i--){
char c = s.charAt(i);
if(c == 'I' || c == 'X' || c == 'C'){
if(i == s.length() - 1){
res = res + map.get(c);
}
else if(map.get(c) < map.get(s.charAt(i+1))){
res = res - map.get(c);
}
else {
res = res + map.get(c);
}
}
else{
res = res + map.get(c);
}
}
return res;
}
}