标签:
这个题目很简单,只是不了解数字与罗马数字转换关系的话就无从下手了。
| 基本字符 | I | V | X | L | C | D | M |
| 对应阿拉伯数字 | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
import java.util.Map;
import java.util.HashMap;
public class Solution {
public int romanToInt(String s) {
Map<Character,Integer> map=new HashMap<Character,Integer>();
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);
int i, total, pre, cur;
total = map.get(s.charAt(0));
for (i = 1; i < s.length(); i++) {
pre = map.get(s.charAt(i - 1));
cur = map.get(s.charAt(i));
if (cur <= pre) {
total += cur;
} else {
total = total - pre * 2 + cur;
}
}
return total;
}
}标签:
原文地址:http://blog.csdn.net/wj512416359/article/details/42040897