这个题目原本很简单的一个Key value就搞定了
其实之前也有过类似的题目但是自己不行了
class Solution {
public String intToRoman(int num) {
String res = ""; // 初始化为空字符串
String str = Integer.toString(num); // 将数字转换为字符串形式
// 处理千位数
if (num / 1000 > 0) {
while (num >= 1000) {
res += "M";
num -= 1000;
}
str = Integer.toString(num); // 更新字符串表示
}
// 处理百位数
if (num / 100 > 0) {
if (str.charAt(0) == '4') {
res += "CD";
num -= 400;
} else if (str.charAt(0) == '9') {
res += "CM";
num -= 900;
} else {
while (num >= 100) {
if (num >= 500) {
res += "D";
num -= 500;
}
while (num >= 100) {
res += "C";
num -= 100;
}
}
}
str = Integer.toString(num); // 更新字符串表示
}
// 处理十位数
if (num / 10 > 0) {
if (str.charAt(0) == '4') {
res += "XL";
num -= 40;
} else if (str.charAt(0) == '9') {
res += "XC";
num -= 90;
} else {
while (num >= 10) {
if (num >= 50) {
res += "L";
num -= 50;
}
while (num >= 10) {
res += "X";
num -= 10;
}
}
}
str = Integer.toString(num); // 更新字符串表示
}
// 处理个位数
if (num > 0) {
if (num == 4) {
res += "IV";
num -= 4;
} else if (num == 9) {
res += "IX";
num -= 9;
} else {
while (num >= 5) {
res += "V";
num -= 5;
}
while (num >= 1) {
res += "I";
num -= 1;
}
}
}
return res; // 返回转换后的罗马数字
}
}
第二种
class Solution {
public String intToRoman(int num) {
// 定义数值和对应的罗马数字符号
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"};
StringBuilder res = new StringBuilder(); // 使用StringBuilder来拼接字符串
// 遍历每个数值和罗马符号
for (int i = 0; i < values.length; i++) {
// 当num大于或等于当前数值时,减去该数值并追加相应的罗马符号
while (num >= values[i]) {
num -= values[i];
res.append(symbols[i]);
}
}
return res.toString(); // 返回结果字符串
}
}