LeetCode:12. Roman to Integer (Easy)

时间:2023-03-09 15:58:02
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. 代码实现

 public class RomantoInteger13 {
public static void main(String[] args) {
System.out.println(RomantoInteger13.romanToInt("MDCCCLXXXIV"));
}
public static int romanToInt(String s) {
int count = 0;
for(int i = s.length()-1;i>=0;i--){
char c = s.charAt(i);
switch (c){
case 'I':
count += (count>=5?-1:1);
break;
case 'V':
count +=5;
break;
case 'X':
count+=(count>=50?-10:10);
break;
case 'L':
count+=50;
break;
case 'C':
count+=(count>=500?-100:100);
break;
case 'D':
count+=500;
break;
case 'M':
count+=1000;
break;
} } return count; }
}