面试经典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;
    }
};
相关推荐
闻缺陷则喜何志丹几秒前
【图论】P9661 [ICPC 2021 Macao R] Sandpile on Clique|普及+
c++·算法·图论·洛谷
时艰.4 分钟前
RocketMQ 面试核心知识点总结
面试·rocketmq
2401_841495645 分钟前
【LeetCode刷题】两两交换链表中的节点
数据结构·python·算法·leetcode·链表·指针·迭代法
傻啦嘿哟16 分钟前
构建命令行单词记忆工具:JSON词库与复习算法的完美结合
算法·json
mjhcsp17 分钟前
一种新的LCA算法
算法
wen__xvn18 分钟前
代码随想录算法训练营DAY24第七章 回溯算法part03
算法·深度优先
无尽的罚坐人生20 分钟前
hot 100 560.和为 K 的子数组
数据结构·算法·leetcode
Ll130452529823 分钟前
leetcode代码随想录数组篇
数据结构·算法·leetcode
问道飞鱼32 分钟前
【大模型学习】大模型应用开发工程师面试核心8问
大数据·学习·面试
Remember_9931 小时前
【LeetCode精选算法】位运算专题一
java·开发语言·数据结构·leetcode·哈希算法