-
Notifications
You must be signed in to change notification settings - Fork 0
/
RomanToInteger.java
88 lines (78 loc) · 2.01 KB
/
RomanToInteger.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package me.rainking;
/**
* @author Rain
* @description
* @date 2018/5/14
*/
public class RomanToInteger {
public static void main(String[] args) {
RomanToInteger obj = new RomanToInteger();
String[] strArr = {"III", "IV", "IX", "LVIII", "MCMXCIV"};
for (String str : strArr)
System.out.println(obj.romanToInt(str));
}
/**
* 不开心不想写代码版
*/
public int romanToInt(String s) {
int[] chArr = new int['Y'];
chArr['I'] = 1;
chArr['V'] = 5;
chArr['X'] = 10;
chArr['L'] = 50;
chArr['C'] = 100;
chArr['D'] = 500;
chArr['M'] = 1000;
int sum = 0;
char preCh;
for (char ch : s.toCharArray()) {
sum += chArr[ch];
}
if (s.contains("IV") || s.contains("IX"))
sum -= 2;
if (s.contains("XL") || s.contains("XC"))
sum -= 20;
if (s.contains("CD") || s.contains("CM"))
sum -= 200;
return sum;
}
/**
* 生活还得继续版
*/
public int romanToInt2(String s) {
int result = 0;
int prev = 1001;
for (char c : s.toCharArray()) {
int curr = 0;
switch (c) {
case 'I':
curr = 1;
break;
case 'V':
curr = 5;
break;
case 'X':
curr = 10;
break;
case 'L':
curr = 50;
break;
case 'C':
curr = 100;
break;
case 'D':
curr = 500;
break;
case 'M':
curr = 1000;
break;
}
if (prev < curr) {
result = result - 2 * prev;
}
result += curr;
prev = curr;
}
return result;
}
}