C++力扣12 整数转罗马数字(中等)

输入:num = 1994

输出:"MCMXCIV"

题意:将整数转罗马数字。罗马数字I-1,V-5,X-10,L-50,C-100,D-500,M-1000,除了这些数之外,其他数就由这些数表示,如II-2,XXVII-27,LIV-54。

1、企图用哈希表来做

只能枚举了。

class Solution {
public:
    string intToRoman(int num) {
        string result;
        unordered_map<int, string>hash = {
            {1, "I"}, {5, "V"}, {10, "X"}, {50, "L"},
            {100, "C"}, {500, "D"}, {1000, "M"}
        };
        while(num>=1000){
            result += "M";
            num -= 1000;
        }
        while(num>=900){
            result += "CM";
            num -= 900;
        }
        while(num>=500){
            result += "D";
            num -= 500;
        }
        while(num>=400){
            result += "CD";
            num -= 400;
        }
        while(num>=100){
            result += "C";
            num -= 100;
        }
        while(num>=90){
            result += "XC";
            num -= 90;
        }
        while(num>=50){
            result += "L";
            num -= 50;
        }
        while(num>=40){
            result += "XL";
            num -= 40;
        }
        while(num>=10){
            result += "X";
            num -= 10;
        }
        while(num>=9){
            result += "IX";
            num -= 9;
        }
        while(num>=5){
            result += "V";
            num -= 5;
        }
        while(num>=4){
            result += "IV";
            num -= 4;
        }
        while(num>=1){
            result += "I";
            num -= 1;
        }
        return result;
    }
};

2、看看官方咋搞

官方跟我上面写的一个意思。就是大大地精简了代码量。主要学到了pair的初始化和遍历。

class Solution {
public:
    string intToRoman(int num) {
        pair<int, string> pair[] = {
            {1000, "M"},
            {900, "CM"},
            {500, "D"}, 
            {400, "CD"}, 
            {100, "C"}, 
            {90, "XC"}, 
            {50, "L"},
            {40, "XL"},
            {10, "X"}, 
            {9, "IX"}, 
            {5, "V"}, 
            {4, "IV"}, 
            {1, "I"}, 
        };
        string result;
        for(auto &[value, symbol] : pair){
            while(num>=value){
                num -= value;
                result += symbol;
            }
        }
        return result;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值