[Leetcode] Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Solution:

此题是要求把罗马数字转换成数字。

首先,学习一下罗马数字,参考罗马数字
 
罗马数字是最古老的数字表示方式,比阿拉伯数组早2000多年,起源于罗马
 
罗马数字有如下符号:
 
基本字符 I V X L C D M
对应阿拉伯数字 1 5 10 50 100 500 1000
计数规则:
  1. 相同的数字连写,所表示的数等于这些数字相加得到的数,例如:III = 3
  2. 小的数字在大的数字右边,所表示的数等于这些数字相加得到的数,例如:VIII = 8
  3. 小的数字,限于(I、X和C)在大的数字左边,所表示的数等于大数减去小数所得的数,例如:IV = 4
  4. 正常使用时,连续的数字重复不得超过三次
  5. 在一个数的上面画横线,表示这个数扩大1000倍(本题只考虑3999以内的数,所以用不到这条规则)
 
其次,罗马数字转阿拉伯数字规则(仅限于3999以内):
 
从前向后遍历罗马数字,如果某个数比后一个数小,则减去该数。反之,加上该数。
 
 1 public class Solution {
 2     public int romanToInt(String s) {
 3         HashMap<Character, Integer> hm=new HashMap<Character, Integer>();
 4         hm.put('M', 1000);
 5         hm.put('D', 500);
 6         hm.put('C', 100);
 7         hm.put('L', 50);
 8         hm.put('X', 10);
 9         hm.put('V', 5);
10         hm.put('I', 1);
11         int result=0;
12         for(int i=0;i<s.length()-1;i++){
13             if(hm.get(s.charAt(i))<hm.get(s.charAt(i+1)))
14                 result-=hm.get(s.charAt(i));
15             else
16                 result+=hm.get(s.charAt(i));
17         }
18         result+=hm.get(s.charAt(s.length()-1));
19         return result;
20     }
21 }
原文地址:https://www.cnblogs.com/Phoebe815/p/4034558.html