leetCode刷题 & 12. 整数转罗马数字

1. 思路

罗马数字的转换可以通过贪心算法来实现。我们可以按照罗马数字的规则,从大到小依次匹配并减去对应的值,直到 num 变为 0。

2. 解题方法

  1. 初始化一个 StringBuilder 用于存储转换后的罗马数字。
  2. 枚举所有的罗马数字符号,按照从大到小的顺序进行匹配:
    • 如果当前数字大于等于当前符号对应的值,则将对应的符号添加到 StringBuilder 中,并从 num 中减去对应的值。
  3. 重复步骤 2 直到 num 变为 0。
  4. 返回 StringBuilder 转换为的字符串。

3. 复杂度

  • 时间复杂度:O(1),因为罗马数字的数量有限,不随输入变化而变化。
  • 空间复杂度:O(1),只需要常数级别的额外空间。

4. Code

java 复制代码
class Solution {
    public String intToRoman(int num) {
        // 用于存储转换后的罗马数字
        StringBuilder roman = new StringBuilder(); 
        
        // 枚举所有的罗马数字符号,按照从大到小的顺序进行匹配
        while (num > 0) {
            if (num >= 1000) {
                roman.append("M");
                num -= 1000;
            } else if (num >= 900) {
                roman.append("CM");
                num -= 900;
            } else if (num >= 500) {
                roman.append("D");
                num -= 500;
            } else if (num >= 400) {
                roman.append("CD");
                num -= 400;
            } else if (num >= 100) {
                roman.append("C");
                num -= 100;
            } else if (num >= 90) {
                roman.append("XC");
                num -= 90;
            } else if (num >= 50) {
                roman.append("L");
                num -= 50;
            } else if (num >= 40) {
                roman.append("XL");
                num -= 40;
            } else if (num >= 10) {
                roman.append("X");
                num -= 10;
            } else if (num >= 9) {
                roman.append("IX");
                num -= 9;
            } else if (num >= 5) {
                roman.append("V");
                num -= 5;
            } else if (num >= 4) {
                roman.append("IV");
                num -= 4;
            } else {
                roman.append("I");
                num -= 1;
            }
        }
        // 返回转换后的罗马数字字符串
        return roman.toString(); 
    }
}

这段代码通过贪心算法实现了将整数转换为罗马数字的功能,按照题目中的规则逐步转换并减去对应的值。

欢迎大家后台联系讨论。

(一份Java面试宝典,有兴趣的读者姥爷可以私信我领取!!!免费滴)

相关推荐
文丑颜不良啊37 分钟前
LeetCode2441~2460题目解析
java·leetcode
文丑颜不良啊2 小时前
LeetCode2521~2540题目解析
java·leetcode
lisw052 小时前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
一起学安全技术3 小时前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs4 小时前
Rust LeetCode238 算法题解
开发语言·算法·rust
自信150413057595 小时前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
文丑颜不良啊5 小时前
LeetCode2501~2520题目解析
java·leetcode
lsc_blog10 小时前
年终自评别贴提交记录,把技术产出讲成变化
数据库·面试·职场和发展·跳槽·求职招聘
GoAI16 小时前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试