【力扣】 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;
    }
};
相关推荐
玛丽莲茼蒿15 小时前
Leetcode hot100 【中等】括号生成
算法·leetcode·职场和发展
小欣加油15 小时前
leetcode 128 最长连续序列
c++·算法·leetcode·职场和发展
汀、人工智能15 小时前
[特殊字符] 第94课:删除无效的括号
数据结构·算法·数据库架构·图论·bfs·删除无效的括号
pwn蒸鱼15 小时前
leetcode:92. 反转链表 II
算法·leetcode·链表
深念Y15 小时前
Harness Engineering:我的HomeSense Agent 架构演进
人工智能·算法·架构·智能家居·agent·小爱同学·harness
Imxyk15 小时前
P9244 [蓝桥杯 2023 省 B] 子串简写
数据结构·c++·算法
colus_SEU15 小时前
SVM 面试题总结
算法·机器学习·支持向量机
INGNIGHT16 小时前
373. 查找和最小的 k 对数字(堆priority_queue)
算法
ambition2024216 小时前
深度优先搜索(DFS)与回溯算法详解:以全排列问题为例
算法·深度优先
Omics Pro16 小时前
马普所:生命蛋白质宇宙聚类
数据库·人工智能·算法·机器学习·数据挖掘·aigc·聚类