【力扣】 12. 整数转罗马数字 模拟

力扣 12. 整数转罗马数字

解题思路

复制代码
	当某个位数的某个数不为4或9时,高位对应的字符总是在低位对应的字符前面。只有当该数为4或9时,低位对应的字符在高位前面。	根据这一特性,我们进行分类讨论。
1.当数为4时,则对应的罗马数为 10 ^ 幂次(对应该数位的次数)加上5 * 10 ^ 幂次。 
如40,则对应的罗马数为 X(10)L(50)。
2.当数为9时,则对应的罗马数为 10 ^ 幂次(对应该数位的次数)加上5  * 10 ^ 幂次。
如90,则对应的罗马数为 X(10)C(100)。
3.当数为其他时,如果大于5,则先加上 5 * 10 ^ 幂次对应的罗马数,再加上 除5余数个数的 10^幂次对应的罗马数。如8,对应的罗马数为 V(5对应的罗马数)III(3个1对应的罗马数)

实现代码

cpp 复制代码
class Solution {
public:
    string intToRoman(int num) {
        int quotient = 1; //当前位数的幂次;
        string resStr = "";
        while(num != 0){
            int mod = num % 10;
            string str;
            if(mod == 9){
                str.append(1, GetRoman(quotient));
                str.append(1, GetRoman(10 * quotient));
            }else if(mod == 4){
                str.append(1,GetRoman(quotient));
                str.append(1, GetRoman(5 * quotient));
            }else{
                if(mod >= 5){
                    str.append(1, GetRoman(5 * quotient));
                }
                mod = num % 5;
                char ch = GetRoman(quotient);
                for(int i = 1; i <= mod; i++)
                    str.append(1, ch);
            }
            resStr = str + resStr;
            quotient *= 10;
            num /= 10;
        }

        return resStr;
    }

    char GetRoman(int value){
        char res;
        switch (value)
        {
            case 1:
                res = 'I';
                break;
            case 5:
                res = 'V';
                break;
            case 10:
                res = 'X';
                break;
            case 50:
                res = 'L';
                break;
            case 100:
                res = 'C';
                break;
            case 500:
                res = 'D';
                break;
            case 1000:
                res = 'M';
                break;
            default:
                break;
        }
        return res;
    }
};
相关推荐
mingo_敏27 分钟前
Mean-Teacher 均值教师自训练框架详解
算法·均值算法
水木流年追梦43 分钟前
agent面试必备31- AI Agent 核心进阶:工具路由(Tool Routing)
数据库·人工智能·oracle·面试·职场和发展·embedding
星空露珠1 小时前
迷你世界UGc3.0脚本Wiki[剧情动画模块管理接口 Timeline]
开发语言·数据结构·算法·游戏·lua
笨笨没好名字1 小时前
Leetcode刷题python3版第一周(下)
linux·算法·leetcode
手写码匠1 小时前
手写 LLM 安全护栏:从内容审核到越狱防御的完整实现
人工智能·深度学习·算法·aigc
luj_17681 小时前
草酸与烟酸对消化及糖代谢的影响解析
服务器·c语言·开发语言·经验分享·算法
青风971 小时前
16-ADAPTRACK:基于自适应阈值的多目标跟踪匹配算法
人工智能·算法·目标跟踪
汤姆yu2 小时前
macOS系统下Aider完整安装、配置与实战使用教程
大数据·人工智能·算法·macos·github·copilot
Sam09272 小时前
【AI 算法精讲 14】TF-IDF:词频与逆文档频率
人工智能·python·算法·ai
AI科技星2 小时前
拓扑生命系统确定性理论:基于32维流形的遗传密码起源与衰老动力学( 中英双语顶刊终稿·标准数学符号)
开发语言·网络·人工智能·算法·机器学习·乖乖数学·全域数学