LeetCode:12. Roman to Integer (Easy)

1. 原题链接

https://leetcode.com/problems/roman-to-integer/description/

2. 题目要求

(1)将罗马数字转换成整数;(2)范围1-3999;

3. 关于罗马数字

   罗马数字相关规则已经在之前一篇博客里写过,这里不再赘述(之前博客的传送门

4. 解题思路

(1)这与之前第十二题Integer转换Roman虽然很相似,但处理方法并不相同。罗马数字更像是一个字符串,因此将其转换成字符数组进行处理。

(2)从后向前遍历一次,结合罗马数字的组合规则,根据该位置罗马数字之前位置累加起来的和进行大小比较,判断该位置是加还是减。

5. 代码实现

 2 
 3 public class RomantoInteger13 {
 4     public static void main(String[] args) {
 5         System.out.println(RomantoInteger13.romanToInt("MDCCCLXXXIV"));
 6     }
 7     public static int romanToInt(String s) {
 8         int count = 0;
 9         for(int i = s.length()-1;i>=0;i--){
10             char c = s.charAt(i);
11             switch (c){
12                 case 'I':
13                     count += (count>=5?-1:1);
14                     break;
15                 case 'V':
16                     count +=5;
17                     break;
18                 case 'X':
19                     count+=(count>=50?-10:10);
20                     break;
21                 case 'L':
22                     count+=50;
23                     break;
24                 case 'C':
25                     count+=(count>=500?-100:100);
26                     break;
27                 case 'D':
28                     count+=500;
29                     break;
30                 case 'M':
31                     count+=1000;
32                     break;
33             }
34 
35         }
36 
37         return count;
38 
39     }
40 }
原文地址:https://www.cnblogs.com/huiAlex/p/8072042.html