思路
比如IXX锰提,使用臨時(shí)變量temp保存上一個(gè)已經(jīng)遍歷的羅馬數(shù)字闷畸,比如:遍歷時(shí)是從后往前遍歷的:1> 剛開始時(shí)播歼,temp = 0; 遍歷當(dāng)前遍歷到第一個(gè)X懊纳,則temp == 0 < 10 == X ,則res = 10;temp = 10;2> 繼續(xù)向前遍歷,又遇到X熏兄,此時(shí)temp == 10 = 10 == X,則 res = res + 10;即res = 20; temp = 10;3> 繼續(xù)向前遍歷品洛,遇到I,此時(shí)temp == 10 > 1 == I; 則 res = res - 1摩桶; 即res = 19; temp = 1;循環(huán)終止桥状;
代碼
public int romanToInt(String s) {
char[] cs = s.toCharArray();
Map<Character, Integer> hm = new HashMap<>();
hm.put('I', 1);
hm.put('V', 5);
hm.put('X', 10);
hm.put('L', 50);
hm.put('C', 100);
hm.put('D', 500);
hm.put('M', 1000);
int res = 0;
int temp = 0; //臨時(shí)變量
int value = 0; //當(dāng)前羅馬值的大小
for (int i = cs.length - 1; i >= 0; i--) {
value = hm.get(cs[i]);
if (temp <= value) {
res += value;
temp = value;
} else {
res -= value;
temp = value;
}
}
return res;
}