leetcode-13罗马字符转整数

leetcode-13罗马字符转整数

  算法:转换的规律是先逐字符按照对应的阿拉伯数字累加,然后对于特殊的(I、X、C出现在左侧)要处理。处理方法:出现特殊字符组合减去双倍的左侧字符(在开始的处理中已经加过一次,而实际的结果中却是要减去,那么就需要在加的基础上减去两倍)。

Code:

vertion : Java

 1 class Solution {
 2     public int romanToInt(String s) {
 3         int ans = 0;
 4         //处理特定字符
 5         if(s.indexOf("IV") != -1)
 6         {
 7             ans += -2;
 8         }
 9         if(s.indexOf("IX") != -1)
10         {
11             ans += -2;
12         }
13         if(s.indexOf("XL") != -1)
14         {
15             ans += -20;
16         }
17         if(s.indexOf("XC") != -1)
18         {
19             ans += -20;
20         }
21         if(s.indexOf("CD") != -1)
22         {
23             ans += -200;
24         }
25         if(s.indexOf("CM") != -1)
26         {
27             ans += -200;
28         }
29         
30         //逐字符处理
31         for(int i=0; i<s.length(); i++)
32         {
33             char c = s.charAt(i);
34             switch(c)
35             {
36                 case 'I':
37                     ans += 1;
38                 break;
39                 case 'V':
40                     ans += 5;
41                 break;
42                 case 'X':
43                     ans += 10;
44                 break;
45                 case 'L':
46                     ans += 50;
47                 break;
48                 case 'C':
49                     ans += 100;
50                 break;
51                 case 'D':
52                     ans += 500;
53                 break;
54                 case 'M':
55                     ans += 1000;
56                 break;
57             }
58         }
59         return ans;
60     }
61 }

猜你喜欢

转载自www.cnblogs.com/yocichen/p/10251073.html