13. Roman to Integer【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.

 1 public class Solution {
 2      public int romanToInt(String s) {
 3         if (s == null || s.length()==0) {
 4                 return 0;
 5         }
 6         Map<Character, Integer> m = new HashMap<Character, Integer>();
 7         m.put('I', 1);
 8         m.put('V', 5);
 9         m.put('X', 10);
10         m.put('L', 50);
11         m.put('C', 100);
12         m.put('D', 500);
13         m.put('M', 1000);
14 
15         int length = s.length();
16         int result = m.get(s.charAt(length - 1));
17         for (int i = length - 2; i >= 0; i--) {
18             if (m.get(s.charAt(i + 1)) <= m.get(s.charAt(i))) {
19                 result += m.get(s.charAt(i));
20             } else {
21                 result -= m.get(s.charAt(i));
22             }
23         }
24         return result;
25     }
26 }
27 
28 // 方法二
29 public class Solution {
30     /**
31      * @param s Roman representation
32      * @return an integer
33      */
34     public int romanToInt(String s) {
35         // Write your code here
36         int ans;
37         char[] sc = s.toCharArray();
38         ans = toInt(sc[0]);                        //0 special
39         for (int i = 1; i < s.length(); i++) {
40             ans += toInt(sc[i]);
41             if (toInt(sc[i - 1]) < toInt(sc[i])) {
42                 ans -= toInt(sc[i - 1]) * 2;
43             }
44         }
45         return ans;
46     }
47 
48     int toInt(char s) {
49         switch(s) {
50             case 'I':return 1;
51             case 'V':return 5;
52             case 'X':return 10;
53             case 'L':return 50;
54             case 'C':return 100;
55             case 'D':return 500;
56             case 'M':return 1000;
57         }
58         return 0;
59     }
60 }

 

转载于:https://www.cnblogs.com/haoHaoStudyShare/p/7308619.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值