leetcode(力扣)第十二题:整数转罗马数字_C++

class Solution {
public:
    string intToRoman(int num) {
        string ans="";
        int temp=num/1000;
        num=num%1000;
        for(int i=temp;i>0;--i) ans+="M";
        
        temp=num/100;
        num=num%100;
        if(temp<4)
            for(int i=temp;i>0;--i) ans+="C";
        else if(temp==4) ans+="CD";
        else if(temp<9){
            ans+="D";
            for(int i=temp;i>5;--i) ans+="C";
        }
        else ans+="CM";

        temp=num/10;
        num=num%10;
        if(temp<4)
            for(int i=temp;i>0;--i) ans+="X";
        else if(temp==4) ans+="XL";
        else if(temp<9){
            ans+="L";
            for(int i=temp;i>5;--i) ans+="X";
        }
        else ans+="XC";

        temp=num;
        if(temp<4)
            for(int i=temp;i>0;--i) ans+="I";
        else if(temp==4) ans+="IV";
        else if(temp<9){
            ans+="V";
            for(int i=temp;i>5;--i) ans+="I";
        }
        else ans+="IX";
        return ans;
    }
};

对3999以下才有用的屑类机械式算法(
讲道理除法耗时略久,所以泛用性小效率也不高,就是不用做表,空间小点。
再转一个力扣上嫖的贪心算法版:

class Solution {
public:
    string intToRoman(int num) {
        string strs[]= {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        int nums[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        string ans;
        for (int i = 0; num > 0 && i < 13; i++) {
            while (nums[i] <= num) {
                ans += strs[i];
                num -= nums[i];
            }
        }
        return ans;
    }
};

每次减去表中能减的最大的数,然后加上对应罗马数字字符,鉴于输入数字再大也就那么点,所以时间复杂度可以算O(1),并且对任意数字有效。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值