forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRomanToInt.java
More file actions
51 lines (48 loc) · 1.12 KB
/
RomanToInt.java
File metadata and controls
51 lines (48 loc) · 1.12 KB
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
package normal;
import java.util.HashMap;
/**
* @program JavaBooks
* @description: 13. 罗马数字转整数
* @author: mf
* @create: 2019/11/10 15:18
*/
/*
题目:https://leetcode-cn.com/problems/roman-to-integer/
难度:easy
*/
/*
输入: "IV"
输出: 4
输入: "IX"
输出: 9
输入: "MCMXCIV"
输出: 1994
解释: M = 1000, CM = 900, XC = 90, IV = 4.
*/
public class RomanToInt {
public static void main(String[] args) {
String s = "MCMXCIV";
System.out.println(romanToInt(s));
}
public static int romanToInt(String s) {
HashMap<Character, Integer> map = new HashMap<>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
int ans = 0, lastValue = 0;
for (int i = s.length() - 1; i >= 0; i--) {
int value = map.get(s.charAt(i));
if (value < lastValue) {
ans -= value;
} else {
ans += value;
}
lastValue = value;
}
return ans;
}
}