面试经典150题——Day18

文章目录

一、题目

12. Integer to Roman

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

Symbol Value

I 1

V 5

X 10

L 50

C 100

D 500

M 1000

For example, 2 is written as II in Roman numeral, just two one's 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.

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

题目来源: leetcode

二、题解

由于num的范围在1~3999之间,因此可以直接使用硬编码的方式解决

cpp 复制代码
class Solution {
public:
    string intToRoman(int num) {
        string thousands[] = {"","M","MM","MMM"};
        string hundreds[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
        string tens[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
        string ones[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};
        string res = thousands[num / 1000] + hundreds[(num % 1000) / 100] + tens[(num % 100) / 10] + ones[num % 10];
        return res;
    }
};
相关推荐
言乐65 分钟前
Python区分广度优先深度优先宽度优先的区别
python·算法·深度优先·广度优先·宽度优先
考研保研资料分享11 分钟前
电气工程保研经验:夏令营失利后上岸上交,科研追问与九推复习(2024)
面试
Rnan-prince18 分钟前
LeetCode 股票买卖系列:一个动态规划状态机模板通吃四题
leetcode·动态规划
如意猴23 分钟前
【C++】007 C/C++ 内存管理机制、malloc与new的区别及模板初阶
java·c++·算法
朝朝辞暮i26 分钟前
C++ 第 32 课:main()、rclcpp::init()、spin()、shutdown()
开发语言·c++·算法
汉克老师31 分钟前
GESP2026年9月认证C++一级( 第三部分编程题(1、新龟兔赛跑))精讲
c++·gesp·小学生·学c++编程
圣保罗的大教堂1 小时前
leetcode 3756. 连接非零数字并乘以其数字和 II 中等
leetcode
沫璃染墨1 小时前
《从零入门Linux系统篇(五十七):线程篇·十——生产者消费者模型进阶:从环形缓冲区到POSIX信号量》
linux·运维·服务器·开发语言·c++·系统架构·信号处理
时间的拾荒人1 小时前
Qt 窗口系统详解:从菜单栏到对话框的完整指南
开发语言·qt·面试
wuminyu1 小时前
LockStack在虚拟线程Mount和Unmount拷贝过程剖析
java·linux·c语言·jvm·c++