罗马数字转整数13

题目如下:

罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。

字符 数值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做  XXVII, 即为 XX + V + II 。

通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:

I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 
C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/roman-to-integer

这道题的解法思路有两种, 一是利用hashmap或者switch判断建立映射关系(小数据量推荐使用switch) 然后将原本的罗马字符串替换为映射关系,然后遍历得到累加值

二是利用"把小值放在大值左边就做减法, 否则做加法"这个规律得到累加值(也要map或者switch,这里推荐使用switch)

java代码如下:

解法一:

public static int romanToInt02(String s) {
s = s.replace("IV", "a").replace("IX", "b").
replace("XL", "c").replace("XC", "d").
replace("CD", "e").replace("CM", "f");

int result = 0;
for (int i = 0; i < s.length(); i++) {
result += which(s.charAt(i));
}
return result;
}

public static int which(char ch) {
switch (ch) {
case 'I':
return 1;

case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
case 'a':
return 4;
case 'b':
return 9;
case 'c':
return 40;
case 'd':
return 90;
case 'e':
return 400;
case 'f':
return 900;
default:
return 0;
}
}
解法二:
public static int romanToInt03(String s) {

int res = 0;
char prestr = s.charAt(0);
char laststr;
for (int i = 1; i < s.length(); i++) {
laststr = s.charAt(i);
if (getValue(prestr) < getValue(laststr)) {
res -= getValue(prestr);
} else {
res += getValue(prestr);
}
prestr = laststr;

}
return res + getValue(s.charAt(s.length() - 1));

}

public static int getValue(char ch) {
switch (ch) {
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
return 0;
}
}
posted @ 2021-03-12 14:25  小猫爱哭鬼  阅读(53)  评论(0编辑  收藏  举报