【LeetCode 面试经典150题】12. Integer to Roman 整数转罗马数字

本文介绍了如何使用贪心算法将整数转换为罗马数字,通过定义整数值和对应字符数组,逐次减去最大可能的罗马数字,直至整数为0,从而得到最简洁的罗马数字表示。
摘要由CSDN通过智能技术生成

12. Integer to Roman

Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M.

SymbolValue
I1
V5
X10
L50
C100
D500
M1000

For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it, making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given an integer, convert it to a Roman numeral.

中文释义

罗马数字由七个不同的符号表示:I、V、X、L、C、D和M。

符号数值
I1
V5
X10
L50
C100
D500
M1000

例如,数字2用罗马数字表示为II,即两个1相加。数字12用XII表示,即X + II。数字27用XXVII表示,即XX + V + II。

罗马数字通常从左到右书写,且大的符号在前,小的符号在后。然而,数字4的表示并不是IIII。相反,数字4用IV表示。因为1在5的前面,所以我们要减去它,得到4。同样的原则适用于数字9,它表示为IX。总共有六种情况需要使用减法规则:

  • I可以放在V(5)和X(10)的前面,得到4和9。
  • X可以放在L(50)和C(100)的前面,得到40和90。
  • C可以放在D(500)和M(1000)的前面,得到400和900。

给定一个整数,将其转换成罗马数字。

Example 1:

Input: num = 3
Output: “III”
Explanation: 3 is represented as 3 ones.

Example 2:

Input: num = 58
Output: “LVIII”
Explanation: L = 50, V = 5, III = 3.

Example 3:

Input: num = 1994
Output: “MCMXCIV”
Explanation: M = 1000, CM = 900, XC = 90, and IV = 4.

Constraints:

1 <= num <= 3999

解题思路

要将整数转换为罗马数字,可以使用贪心算法的思想,从最大的罗马数字开始逐步减去,直到整数为0为止。

  1. 首先,定义两个数组 valuesreps,分别存储罗马数字的整数值和对应的罗马字符。

  2. 创建一个空字符串 res 用于存储最终的罗马数字表示。

  3. 使用循环遍历 valuesreps 数组,从最大的罗马数字开始向最小的罗马数字遍历。

  4. 在每次循环中,检查当前整数 num 是否大于或等于 values[i],如果是,就将 values[i]num 中减去,并将对应的罗马字符 reps[i] 添加到结果字符串 res 中。

  5. 重复步骤4,直到 num 变为0。

  6. 返回结果字符串 res 作为整数对应的罗马数字表示。

这个算法的关键思想是尽可能多地使用大的罗马数字来表示整数,以得到最简洁的罗马数字表示。

class Solution {
public:
    string intToRoman(int num) {
        int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        string reps[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        
        string res;
        for(int i = 0; i < 13; i++) {
            while(num >= values[i]) {
                num -= values[i];
                res += reps[i];
            }
        }
        return res;
    }
};
  • 24
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值