728x90
반응형
Python
from collections import OrderedDict
class Solution:
def __init__(self):
self.symbol_dict = OrderedDict({
1000: "M",
900: "CM",
500: "D",
400: "CD",
100: "C",
90: "XC",
50: "L",
40: "XL",
10: "X",
9: "IX",
5: "V",
4: "IV",
1: "I",
})
def intToRoman(self, num: int) -> str:
answer = ""
for k, v in self.symbol_dict.items():
if num // k > 0:
result = num // k
answer += v * result
num = num % k
return answer
Java
1.
import java.util.LinkedHashMap;
class Solution {
public HashMap<Integer, String> symbolMap;
public Solution() {
super();
this.symbolMap = new LinkedHashMap<Integer, String>();
this.symbolMap.put(1000, "M");
this.symbolMap.put(900, "CM");
this.symbolMap.put(500, "D");
this.symbolMap.put(400, "CD");
this.symbolMap.put(100, "C");
this.symbolMap.put(90, "XC");
this.symbolMap.put(50, "L");
this.symbolMap.put(40, "XL");
this.symbolMap.put(10, "X");
this.symbolMap.put(9, "IX");
this.symbolMap.put(5, "V");
this.symbolMap.put(4, "IV");
this.symbolMap.put(1, "I");
}
public String intToRoman(int num) {
String answer = "";
for (Integer key: this.symbolMap.keySet()) {
int quotient = num / key;
num %= key;
for (int i = 0; i < quotient; i++) {
answer += this.symbolMap.get(key);
}
}
return answer;
}
}
2.
import java.util.LinkedHashMap;
class Solution {
public Object[][] symbolArray = {
{1000, "M"},
{900, "CM"},
{500, "D"},
{400, "CD"},
{100, "C"},
{90, "XC"},
{50, "L"},
{40, "XL"},
{10, "X"},
{9, "IX"},
{5, "V"},
{4, "IV"},
{1, "I"}
};
public String intToRoman(int num) {
String answer = "";
for (Object[] mapArray: this.symbolArray) {
int quotient = num / (int)mapArray[0];
num %= (int)mapArray[0];
for (int i = 0; i < quotient; i++) {
answer += (String)mapArray[1];
}
}
return answer;
}
}
728x90
반응형
'LeetCode > Medium' 카테고리의 다른 글
29. Divide Two Integers (0) | 2022.03.30 |
---|---|
11. Container With Most Water (0) | 2022.03.28 |
15. 3Sum (0) | 2022.03.24 |
8. String to Integer (atoi) (0) | 2022.03.22 |
7. Reverse Integer (0) | 2022.03.21 |