罗马计数:
I - 1
V - 5
X - 10
L - 50
C - 100
D - 500
M - 1000
If a lower value symbol is before a higher value one, it is subtracted. Otherwise it is added.So 'IV' is '4' and 'VI' is '6'.(数字小的符号在数字大的符号之前,则为减法;否则为加法)
以上参考维基百科:http://simple.wikipedia.org/wiki/Roman_numeral。
具体编码则跟据以上的策略,着重分析相邻两个符号所代表的数字的大小关系以确定 加或者减。
public class Solution {
private final Map<Character,Integer> map ;
public Solution(){
map = new HashMap<>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
}
public int romanToInt(String s) {
int pre = 0;
int cur = 1;
int count = 0;
for(pre=0,cur=1;cur<s.length();++pre,++cur){
int preNum = map.get(s.charAt(pre));
int curNum = map.get(s.charAt(cur));
if(preNum< curNum){
count -= preNum;
}else{
count += preNum;
}
}
count += map.get(s.charAt(pre));
return count;
}
}