Leetcode Q12 整数转罗马数字

在这里插入图片描述
原题地址

思路先从大的开始然后一步步往下除,然后由大往小进行换算.这个属于贪心算法
实现方法:
1.比较直接的就是if else进行实现
2.简洁一点则是使用字典来用循环进行实现.不过java的字典初始化蛮麻烦的,就用两个数组代替了.

代码

 public String intToRoman1(int num) {
        String res = "";
        int values[]={1000,900,500,400,100,90,50,40,10,9,5,4,1};
        String reps[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        int i=0;
        while(num!=0){
            if(num>=values[i]){
                for(int q=0;q<num/values[i];q++)
                res += reps[i];
            }
            else i++;
        }
        return res;
    }
    public String intToRoman(int num) {
        String res = "";
        int i = 0;
        for (i = 0; i < num / 1000; i++) {
            res += "M";
        }
        num -= i * 1000;
        if (num / 900 >= 1) {
            res += "CM";
            num -= 900;
        }
        if (num / 500 >= 1) {
            res += "D";
            num -= 500;
        }
        if (num / 400 >= 1) {
            res += "CD";
            num -= 400;
        }
        for (i = 0; i < num / 100; i++) {
            res += "C";
        }
        num -= i * 100;
        if (num / 90 >= 1) {
            res += "XC";
            num -= 90;
        }

        if (num / 50 >= 1) {
            res += "L";
            num -= 50;
        }
        if (num / 40 >= 1) {
            res += "XL";
            num -= 40;
        }
        for (i = 0; i < num / 10; i++) {
            res += "X";
        }
        num -= i * 10;
        if (num / 9 >= 1) {
            res += "IX";
            num -= 9;
        }
        if (num / 5 >= 1) {
            res += "V";
            num -= 5;
        }
        if (num / 4 >= 1) {
            res += "IV";
            num -= 4;
        }
        for (i = 0; i < num / 1; i++) {
            res += "I";
        }
        return res;
    }

还有一个比较有趣的方法,硬编码

public String intToRoman(int num) {
    
    String[] thousands = {"", "M", "MM", "MMM"};
    String[] hundreds = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 
    String[] tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
    String[] ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
    
    return thousands[num / 1000] + hundreds[num % 1000 / 100] + tens[num % 100 / 10] + ones[num % 10];
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/integer-to-roman/solution/zheng-shu-zhuan-luo-ma-shu-zi-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rglkt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值