# 每日一题(1):罗马数字转整数
# 开始
先从简单难度开刷,这道题本身不难,但是思路却有很多
核心思想是用Map来做字符到数值的映射,这样可以替换成数字来累加计算
然后"左小右大"的特殊情况,有几种思路可以处理
可以暴力全局字符匹配再替换(性能扑街),也可以先加后减
我个人思路如下:
package org.example.helloworld;
public class Main {
public static void main(String[] args) {
String s = "MCMXCIV";
int sum = 0;
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; i++) {
char curr = cs[i];
char next = i == cs.length - 1 ? 'A' : cs[i + 1];
int currNum = map(curr);
int nextNum = map(next);
if (currNum >= nextNum) {
sum += currNum;
} else {
sum += nextNum - currNum;
i++;
}
}
System.out.println(sum);
}
private static int map(char c) {
switch(c) {
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;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
文字表达就是遍历输入字符串
拿到curr和next(若curr是最后一位了,next就给个'A'==0)
然后判断curr和next大小关系
curr大next小:正常累加
next大curr小:相减再累加,并跳过一位
好像没什么人是这个思路,可能我思路比较清奇哈哈,但是一看性能(扑街)
这里还看了大神思路才把Map优化成switch-case
不过实际项目中应该不常这么干哈哈
明天继续~