码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 13.Roman to Integer 罗马数字转阿拉伯数字

时间:2017-06-19 15:19:02      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:for   ash   log   roman   new   str   情况   数字   color   

对于罗马数字转阿拉伯数字切入点有两个:

  1、小数字出现在大数字前面只能使用一个(例如IV正确,IIV就是错误的)

  2、除了情况1之外直接使用累加就ok

  

 1     public int romanToInt(String s){
 2         if(s.length() < 1){
 3             return 0;
 4         }
 5         int result = 0;
 6         for(int i=0;i<s.length();i++){
 7             result += getRomanValue(s.charAt(i));
 8             if(i<s.length()-1){
 9                 if( getRomanValue(s.charAt(i)) < getRomanValue(s.charAt(i+1)) ){
10                     result -= 2*getRomanValue(s.charAt(i));
11                 }
12             }
13         }
14         return result;
15     }
16     public int getRomanValue(char c){
17         Map<Character,Integer> map = new HashMap<Character, Integer>();
18         map.put(‘I‘,1);
19         map.put(‘V‘,5);
20         map.put(‘X‘,10);
21         map.put(‘L‘,50);
22         map.put(‘C‘,100);
23         map.put(‘D‘,500);
24         map.put(‘M‘,1000);
25         return map.get(c);
26     }

 

  

LeetCode 13.Roman to Integer 罗马数字转阿拉伯数字

标签:for   ash   log   roman   new   str   情况   数字   color   

原文地址:http://www.cnblogs.com/smilecoder/p/7048581.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!