您的位置:首页 > 其它

Roman to Integer 罗马数字转化成整数

2017-08-23 10:30 519 查看
题目:https://leetcode.com/problems/roman-to-integer/description/

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.
题目大意:
将罗马数字转换成整数。

解法:

1、罗马数字放进map,数字一一对应,

2、字符串每个都分割,从map中取出对应的值

3、第一,如果当前数字是最后一个数字,或者之后的数字小于等于他(<=)的话,则加上当前数字
第二,其他情况则减去这个数字

public static int romanToInt(String s) {
int result=0;
//1、罗马数字放进map,数字一一对应,
Map<Character, Integer> romanInteger=new HashMap<Character, Integer>();
romanInteger.put('I', 1);
romanInteger.put('V', 5);
romanInteger.put('X', 10);
romanInteger.put('L', 50);
romanInteger.put('C', 100);
romanInteger.put('D', 500);
romanInteger.put('M', 1000);
//2、字符串每个都分割,从map中取出对应的值
for (int i = 0; i < s.length(); i++) {
if(i==s.length()-1){
//如果当前数字是最后一个数字,加上
result+=romanInteger.get(s.charAt(i));
continue;
}
//之后的数字比它小的话,则加上当前数字
boolean compare=false;
for (int j = i+1; j < s.length(); j++) {
if(romanInteger.get(s.charAt(i))<romanInteger.get(s.charAt(j))){
compare=true;
}
}
if(!compare){
result+=romanInteger.get(s.charAt(i));
continue;
}
//除此之外,则减去当前数字
result-=romanInteger.get(s.charAt(i));
}
return result;

}

参考自:http://www.cnblogs.com/grandyang/p/4120857.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: