您的位置:首页 > 其它

Roman to Integer

2015-08-12 11:25 295 查看
如果当前字符小于前个字符对应的数字加上当前字符对应的数字减去前一个数字的两倍 否则直接加上当前数字就好

public class Solutiion {
public static int romanToInt(String s) {

char[] symbol = { 'I', 'V', 'X', 'L', 'C', 'D', 'M' };
int[] val = { 1, 5, 10, 50, 100, 500, 1000 };
Map<Character, Integer> map = new HashMap<Character, Integer>();
int i, k = 0;
int left, result = 0;
for (i = 0; i < symbol.length; i++) {
map.put(symbol[i], val[i]);
}
left = map.get(s.charAt(0));
result = result + left;
if (s.length() == 1) {
return map.get(s.charAt(0));
}
for (i = 1; i < s.length(); i++) {

if (map.get(s.charAt(i)) <= map.get(s.charAt(i - 1))) {
result = result + map.get(s.charAt(i));
} else {
result = result + map.get(s.charAt(i)) - 2 * map.get(s.charAt(i - 1));
}
}
return result;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: