[LeetCode]-011-Roman_to_Integer

Given a roman numeral, convert it to an integer.

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

题目大意:把罗马数字转换成的整数

遍历每个字符,前一个字符比后一个字符小,相减

 1 public class Solution{
 2     public int romanToInt(String s) {
 3         s = s.trim();
 4         if (null == s || "".equals(s))
 5             return 0;
 6         HashMap<Character,Integer> map = new HashMap<Character,Integer>();
 7         map.put('I',1);
 8         map.put('V',5);
 9         map.put('X',10);
10         map.put('L',50);
11         map.put('C',100);
12         map.put('D',500);
13         map.put('M',1000);
14         int cur = s.length()-1;
15         int sum = map.get(s.charAt(cur));
16         int tmp1,tmp2;
17         cur--;
18         while(cur>=0){
19             tmp1 = map.get(s.charAt(cur+1));
20             tmp2 = map.get(s.charAt(cur));
21             if(tmp2<tmp1)
22                 sum = sum - tmp2;
23             else
24                 sum = sum + tmp2;
25             cur--;
26         }
27         return sum;
28     }
29     
30     public static void main(String[] args){
31         String param = "CMXLVI";
32         if(args.length==1){
33             param = args[0];
34         }
35         Solution solution = new Solution();
36         int res = solution.romanToInt(param);
37         System.out.println(res);
38     }
39 }

 

posted @ 2016-04-18 10:58  练子  阅读(120)  评论(0编辑  收藏  举报