LeetCoder 12. Integer to Roman
来源:互联网 发布:双mic降噪 算法 编辑:程序博客网 时间:2024/05/18 03:39
题意
将一个数字转换为罗马数字.
什么是罗马数字呢?就是我们钟表上面的时刻,例如:
思路
关于罗马数字的规则和解释在这里:罗马数字
因为题目规定数字最大为3999,所以说,我们可以根据这个打一个表
M[] = {"", "M", "MM", "MMM"};C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};I[] = {"", "I", "4II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
根据表进行组合即可.
结果
Your runtime beats 67.78 % of cpp submissions.
代码
class Solution {public: string intToRoman(int num) { string ans = ""; int cnt = num / 1000; for(int i = 0; i < cnt;i++){ ans += "M"; } num = num % 1000; addRoman(100, num / 100, ans); num = num % 100; addRoman(10, num / 10, ans); num = num %10; addRoman(1, num, ans); return ans; } void addRoman(int level, int cnt, string &ans){ string Left, Mid, Right; if(level == 100){ Left = "C"; Mid = "D"; Right = "M"; } else if(level == 10){ Left = "X"; Mid = "L"; Right = "C"; } else{ Left = "I"; Mid = "V"; Right = "X"; } if(cnt <= 3){ for(int i = 0; i < cnt;i++){ ans += Left; } } else if(cnt == 4){ ans = ans + Left + Mid; } else if(cnt <= 8){ ans += Mid; for(int i = 0;i < cnt - 5;i++){ ans += Left; } } else{ ans = ans + Left + Right; } }};
0 0
- LeetCoder 12. Integer to Roman
- LeetCoder 13. Roman to Integer
- 12.Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 《假如给我三天光明》读后感及其摘录(2)
- MysqlDump某表的一部分列
- 散列表
- 什么是人工智能、机器学习、深度学习、数据挖掘以及数据分析?<二>
- 蓝桥杯 基础练习 杨辉三角形 JAVA
- LeetCoder 12. Integer to Roman
- 一道经典的深搜题,不易写满分(素数环)
- CSS中一些重要概念
- Ubuntu下配置支持Windows访问的samba共享
- windows7 64位下安装tensorflow终极解决方案
- 初识STL中的unique函数
- 集合框架-LinkedHashMap的概述和使用
- 《程序员修炼之道》笔记(四)
- SpringMVC 确定目标方法 POJO 类型入参的过程