0
点赞
收藏
分享

微信扫一扫

【LeeCode】12. 整数转罗马数字

【题目描述】

罗马数字包含以下七种字符: ​I​, ​V​, ​X​, ​L​​C​​D​ 和 ​M​


【示例】

【LeeCode】12. 整数转罗马数字_罗马数字

【代码】​​liweiwei1419​​

import java.awt.image.ImageProducer;
import java.util.*;
import java.util.stream.Collectors;
// 2022-12-19

class Solution {
public String intToRoman(int num) {
String res = "";
// 把阿拉伯数字与罗马数字可能出现的所有情况和对应关系,放在两个数组中,并且按照阿拉伯数字的大小降序排列
int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

StringBuilder sb = new StringBuilder();
int index = 0;
while (index < 13) {
while (num >= nums[index]) {
sb.append(romans[index]);
num -= nums[index];
}
index++;
}
res = sb.toString();
return res;
}
}
public class Main{
public static void main(String[] args) {
int arr = 58;
new Solution().intToRoman(arr); // 输出: LVIII
}
}

【代码】官方

【LeeCode】12. 整数转罗马数字_数组_02

举报

相关推荐

0 条评论