当前位置:网站首页>【LeetCode】12、整数转罗马数字
【LeetCode】12、整数转罗马数字
2022-06-28 05:05:00 【小曲同学呀】
12、整数转罗马数字
题目:
罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
字符 数值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。
通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:
I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
给你一个整数,将其转为罗马数字。
示例1:
输入: num = 3
输出: "III"
示例 2:
输入: num = 4
输出: "IV"
示例 3:
输入: num = 9
输出: "IX"
示例 4:
输入: num = 58
输出: "LVIII"
解释: L = 50, V = 5, III = 3.
示例 5:
输入: num = 1994
输出: "MCMXCIV"
解释: M = 1000, CM = 900, XC = 90, IV = 4.
解题思路:
此题的解题思路,比较多,比如贪心算法,暴力拆解,枚举。拼接等等。
咱们就用拼接法来实现一下:
参考代码:
class Solution {
public String intToRoman(int num) {
int[] values={
1000,900,500,400,100,90,50,40,10,9,5,4,1};
String[] rom={
"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
StringBuilder sb=new StringBuilder();
for(int i=0;i<values.length;i++){
while(num>=values[i]){
sb.append(rom[i]);
num-=values[i];
}
}
return sb.toString();
}
}

边栏推荐
- Distributed transaction - Final consistency scheme based on message compensation (local message table, message queue)
- BioVendor sRAGE Elisa试剂盒化学性质和技术研究
- Congratulations to myself, official account has more than ten thousand fans
- Excel将一行的内容进行复制时,列与列之间是用制表符“\t”进行分隔的
- Unity out ref params
- 2022 safety officer-b certificate examination question bank and answers
- 2022烟花爆竹经营单位安全管理人员特种作业证考试题库及模拟考试
- [CSP-J2020] 优秀的拆分
- mysql----where 1=1是什么意思
- IP数据报的发送和转发过程
猜你喜欢

Amino dye research: lumiprobe fam amine, 6-isomer

学习太极创客 — MQTT 第二章(四)ESP8266 保留消息应用

Dart学习——函数、类

并发之wait/notify说明

分享一个因子挖掘的利器:遗传规划

Sword finger offer 47 Maximum gift value (DP)

2022 high altitude installation, maintenance and removal examination questions and answers

Function and working principle of controller

CI & CD must be known!

交流电和直流电的区别是什么?
随机推荐
QCOM LCD调试
S32ds jump to defaultisr
Learning Tai Chi Maker - mqtt Chapter 2 (V) heartbeat mechanism
Role of native keyword
[skywalking] learn distributed link tracking skywalking at one go
Feign implements path escape through custom annotations
openssl客户端编程:一个不起眼的函数导致的SSL会话失败问题
PCR/qPCR研究:Lumiprobe丨dsGreen 用于实时 PCR
2022烟花爆竹经营单位安全管理人员特种作业证考试题库及模拟考试
Severe tire damage: the first rock band in the world to broadcast live on the Internet
BioVendor sRAGE抗体解决方案
Carboxylic acid study: lumiprobe sulfoacyanine 7 dicarboxylic acid
lotus v1.16.0 calibnet
Lumiprobe cell imaging analysis: PKH26 cell membrane labeling kit
[JVM series] JVM tuning
Where does the storm go? Whose pot is the weather forecast wrong?
Biovendor sRAGE protein solution
Unity delegate
Sword finger offer 47 Maximum gift value (DP)
创新之源 理解通透 二