1. 首页
  2. 软件开发
  3. day-56 整数转罗马数字

day-56 整数转罗马数字

  • 发布于 2024-09-26
  • 12 次阅读


思路
因为题目已经告知num<=3999,所以只需依次对1000,900,500,400,100,90,50,40,10,9,5,4,1这些数进行除法,判断商是否大于等于1,如果大于等于1则将对应的罗马数字拼接到字符串中即可

解题过程
为了方便拼接,可以使用哈希键值对,key为整数,value为对应的罗马数字

Code

class Solution {

    public String intToRoman(int num) {

        Map<Integer,String> map=new HashMap<>();
        map.put(1,"I");
        map.put(4,"IV");
        map.put(5,"V");
        map.put(9,"IX");
        map.put(10,"X");
        map.put(40,"XL");
        map.put(50,"L");
        map.put(90,"XC");
        map.put(100,"C");
        map.put(400,"CD");
        map.put(500,"D");
        map.put(900,"CM");
        map.put(1000,"M");
        int arr[]={
   1000,900,500,400,100,90,50,40,10,9,5,4,1};
        String ans="";
        int id=0;
        while(id<13&&num>0){

            if(num/arr[id]!=0){

                ans+=map.get(arr[id]);
                num=num-arr[id];
            }else{

                id++;
            }
        }
        return ans;
    }
}

作者:菜卷
链接:https://leetcode.cn/problems/integer-to-roman/solutions/2923381/zheng-shu-zhuan-luo-ma-shu-zi-by-ashi-ji-vz7b/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

原文链接: https://blog.csdn.net/qq_53568730/article/details/142376292