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

leetcode-13罗马字符转整数

时间:2019-01-10 17:45:22      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:public   图片   .com   turn   特殊字符   cas   方法   indexof   ring   

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 }

 

leetcode-13罗马字符转整数

标签:public   图片   .com   turn   特殊字符   cas   方法   indexof   ring   

原文地址:https://www.cnblogs.com/yocichen/p/10251073.html

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