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

来源:互联网 发布:天府商品交易软件 编辑:程序博客网 时间:2024/05/16 18:24

题目: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




原创粉丝点击