【力扣】 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;
    }
};
相关推荐
孤飞1 小时前
zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线
算法
zjeweler2 小时前
“网安+护网”终极300多问题面试笔记-3共3-综合题型(最多)
笔记·网络安全·面试·职场和发展·护网行动
技术专家2 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
Hacker_Nightrain3 小时前
详解Selenium 和Playwright两大框架的不同之处
自动化测试·软件测试·selenium·测试工具·职场和发展
csdn_aspnet3 小时前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
鹿角片ljp3 小时前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
paeamecium4 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
chh5635 小时前
C++--模版初阶
c语言·开发语言·c++·学习·算法
RTC老炮6 小时前
带宽估计算法(gcc++)架构设计及优化
网络·算法·webrtc
dsyyyyy11016 小时前
计数孤岛(DFS和BFS解决)
算法·深度优先·宽度优先