面试经典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;
    }
};
相关推荐
二进制person4 小时前
Java SE--方法的使用
java·开发语言·算法
OneQ6664 小时前
C++讲解---创建日期类
开发语言·c++·算法
JoJo_Way4 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
.30-06Springfield5 小时前
人工智能概念之七:集成学习思想(Bagging、Boosting、Stacking)
人工智能·算法·机器学习·集成学习
Coding小公仔7 小时前
C++ bitset 模板类
开发语言·c++
凌肖战7 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
菜鸟看点7 小时前
自定义Cereal XML输出容器节点
c++·qt
weixin_478689767 小时前
十大排序算法汇总
java·算法·排序算法
luofeiju8 小时前
使用LU分解求解线性方程组
线性代数·算法
天涯学馆8 小时前
前端开发也能用 WebAssembly?这些场景超实用!
前端·javascript·面试