-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntToRoman.java
More file actions
80 lines (62 loc) · 2.04 KB
/
Copy pathIntToRoman.java
File metadata and controls
80 lines (62 loc) · 2.04 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.leetcode.string;
import java.util.HashMap;
import java.util.Map;
public class IntToRoman {
public String intToRoman(int num) {
int[] nums = new int[]{1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
String[] chars = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
StringBuilder sb = new StringBuilder();
for (int i = nums.length - 1; i >= 0; ) {
if (num == nums[i]) {
sb.append(chars[i]);
break;
} else if (num > nums[i]) {
sb.append(chars[i]);
num -= nums[i];
} else {
i--;
}
}
return sb.toString();
}
/**
*
*/
String[] thousands = {"", "M", "MM", "MMM"};
String[] hundreds = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
String[] tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
String[] ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
public String intToRomanSuper(int num) {
StringBuffer roman = new StringBuffer();
roman.append(thousands[num / 1000]);
roman.append(hundreds[num % 1000 / 100]);
roman.append(tens[num % 100 / 10]);
roman.append(ones[num % 10]);
return roman.toString();
}
Map<Character, Integer> map = new HashMap<Character,Integer>(){{
put('I', 1);
put('V', 5);
put('X', 10);
put('L', 50);
put('C', 100);
put('D', 500);
put('M', 1000);
}};
public int romanToInt(String s) {
int len = s.length();
int ans = 0;
for(int i=0;i<len;i++){
int curVal = map.get(s.charAt(i));
if (i < len - 1 && curVal < map.get(s.charAt(i + 1))) {
ans -= curVal;
}else{
ans +=curVal;
}
}
return ans;
}
public static void main(String[] args) {
new IntToRoman().romanToInt("MCMXCIV");
}
}