leetcode 12. 整数转罗马数字
replace法,但是比较耗时
public String intToRoman(int num) {
String rawStr = firstConvert(num);
rawStr = rawStr.replace("DCCCC", "CM");
rawStr = rawStr.replace("CCCC", "CD");
rawStr = rawStr.replace("LXXXX", "XC");
rawStr = rawStr.replace("XXXX", "XL");
rawStr = rawStr.replace("VIIII", "IX");
rawStr = rawStr.replace("IIII", "IV");
return rawStr;
}
public String firstConvert(int num) {
Map<String, Integer> table = new HashMap<>();
table.put("I", 1);
table.put("V", 5);
table.put("X", 10);
table.put("L", 50);
table.put("C", 100);
table.put("D", 500);
table.put("M", 1000);
StringBuilder res = new StringBuilder();
int remain = num;
// 1000
int M = remain / table.get("M");
becomeStr(res, "M", M);
remain = remain % table.get("M");
// 500
int D = remain / table.get("D");
becomeStr(res, "D", D);
remain = remain % table.get("D");
// 100
int C = remain / table.get("C");
becomeStr(res, "C", C);
remain = remain % table.get("C");
// 50
int L = remain / table.get("L");
becomeStr(res, "L", L);
remain = remain % table.get("L");
// 10
int X = remain / table.get("X");
becomeStr(res, "X", X);
remain = remain % table.get("X");
// 5
int V = remain / table.get("V");
becomeStr(res, "V", V);
remain = remain % table.get("V");
becomeStr(res, "I", remain);
return res.toString();
}
public void becomeStr(StringBuilder sb, String str, int times) {
for (int i = 0; i < times; i++) {
sb.append(str);
}
}
直接法
这题其实只要从大到小一 一 遍 历 一遍就行。
class Solution {
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
public String intToRoman(int num) {
StringBuffer roman = new StringBuffer();
for (int i = 0; i < values.length; ++i) {
int value = values[i];
String symbol = symbols[i];
while (num >= value) {
num -= value;
roman.append(symbol);
}
if (num == 0) {
break;
}
}
return roman.toString();
}
}