【力扣】 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;
    }
};
相关推荐
凌冰_9 小时前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
Pniubi10 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展
戴·菲瑜10 小时前
为什么PPO难以做出顶级棋类引擎
算法·博弈论·rl·ppo
在所不辞兄12 小时前
为什么数字孪生驱动的产线标定需要在线更新机制,而不能一次标定后长期沿用?
人工智能·神经网络·其他·算法·机器学习
文丑颜不良啊16 小时前
LeetCode3401~3420题目解析
java·leetcode
AvocadoZeroOneOI17 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
文丑颜不良啊17 小时前
LeetCode3421~3440题目解析
java·leetcode
cjz389919 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
橘子131 天前
【高级数据库】关系代数基本概念
算法
电科_银尘1 天前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法