-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRomanToInteger.java
More file actions
56 lines (40 loc) · 1.14 KB
/
Copy pathRomanToInteger.java
File metadata and controls
56 lines (40 loc) · 1.14 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
52
53
54
55
56
import java.util.*;
public class Roman {
public static int romanToInt(String s) {
HashMap<Character,Integer> h = new HashMap<Character,Integer>();
h.put('I',1);
h.put('V',5);
h.put('X',10);
h.put('L',50);
h.put('C',100);
h.put('D',500);
h.put('M',1000);
if(s.length()==1)
return h.get(s.charAt(0));
int res=0,t=0;
boolean flg = true;
res = h.get(s.charAt(s.length()-1));
int x=s.length()-1;
for(int i=s.length()-2;i>0;--i)
{
t=h.get(s.charAt(i));
flg = (h.get(s.charAt(i))>=h.get(s.charAt(x))) ? true:false;
if(flg)
res+=t;
else
res-=t;
--x;
}
t=h.get(s.charAt(0));
flg = (h.get(s.charAt(0))>=h.get(s.charAt(1))) ? true:false;
if(flg)
res+=t;
else
res-=t;
return res;
}
public static void main(String[] args)
{
System.out.println(romanToInt("MMMDXLIV"));
}
}